Abhishek
Abhishek

Reputation: 783

Android: OptionalDataException upon ObjectInputStream.readObject()

Situation : From my Android server, I'm sending a simple String OBJECT to the client. I use ObjectOutputStream at the server, and ObjectInputStream at the client.

Server code:

            mOutput.flush();
            mOutput.reset();

            Object myStr = new String(res); //res is some String
            mOutput.writeObject(myStr);
            mOutput.flush();

Client Code:

            Log.v("CLIENT","Attempting to receive results from Server");

            obj = objectInputStream.readObject(); //ERROR THROWN HERE

            Log.v("CLIENT", "Object received");

            res = (String)obj;

Problem : At the client end, I get an OptionalDataException during readObject(). The interesting thing is, that its able to read it properly only for the first time, but subsequently throws this exception.

As you can see, I flush() and reset() the OutPutStream before and after sending the object. Why does this error still occur ?

Upvotes: -1

Views: 259

Answers (1)

Abhishek
Abhishek

Reputation: 783

Problem solved. Android's documentation says that there should be no leftover primitives in the ObjectOutputStream when sending objects.

It turns out I was also writing a byte (using writeBytes()) after sending the object. The flush() and reset() did not remove this stray byte in the ObjectOutputStream, and hence the ObjectInputStream reported an OptionalDataException.

Make sure you also remove any stray ObjectOutputStream.writeInt(), writeBoolean(), writeUTF() or writeChars() or whatever before you read the ObjectInputStream ...Otherwise this exception will be thrown !

Wonder why the prior and immediate flush() and reset() did not work ?

Upvotes: -1

Related Questions