Why do I get a ClassCastException when trying to cast stream from socket?

935 views Asked by At

I am trying to establish a bluetooth connection between my Android app (the client) and my python server. However, I have got a problem with the streams. This piece of code throws a ClassCastException and I don't know why and how to fix it. Any ideas or tips?

public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "create ConnectedThread");
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            // THIS IS WHERE THE EXCEPTION IS THROWN
            tmpIn = (DataInputStream) socket.getInputStream(); 
            tmpOut = (DataOutputStream) socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
1

There are 1 answers

0
Matt On BEST ANSWER

Socket.getInputStream() returns an InputStream, not a DataInputStream. Socket.getOutputStream() returns an OutputStream, not a DataOutputStream. You shouldn't cast from an InputStream or OutputStream to a sub-class unless you're 100% sure of the type. You can, however, create a DataInputStream or DataOutputStream from raw InputStreams and OutputStreams (see below).

You can just remove the cast to make your code look like this (you'll also need to create a new DataInputStream and new DataOutputStream if that's what the mmInStream and mmOutStream vars are):

public ConnectedThread(BluetoothSocket socket) {
    Log.d(TAG, "create ConnectedThread");
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the BluetoothSocket input and output streams
    try {
        tmpIn = socket.getInputStream(); 
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Log.e(TAG, "temp sockets not created", e);
    }
    mmInStream = new DataInputStream(tmpIn);
    mmOutStream = new DataOutputStream(tmpOut);
}

(PS. Don't forget to close your streams!)