0

I verified from the java docs that boolean and byte are serializable. As per the android docs, my class implements the serializable interface. I am not sure why I keep getting the exception. What am I missing here? The class is like this:

public class msgStruct implements Serializable {
    boolean pingPong = false; 
    int msgId = 0;
    byte[] bufferMsg = new byte[100];
}

This is serialized before being sent via a socket to the server, like this:

sendMsgStruct.pingPong = false;
sendMsgStruct.msgId = msgId;
rand.nextBytes(sendMsgStruct.bufferMsg);
try {
    ObjectOutputStream serializeMobile = new ObjectOutputStream(mobileSocket.getOutputStream());
    serializeMobile.writeObject(sendMsgStruct);
    serializeMobile.close();
} catch (IOException e1) {
    e1.printStackTrace();
    return false;
} 

The server deserializes like this:

try {
     ObjectInputStream deserializeServer = new ObjectInputStream(clientSocket.getInputStream());
     recvMsgStruct = (msgStruct) deserializeServer.readObject();
     deserializeServer.close();
    } catch (ClassNotFoundException e1) {
      e1.printStackTrace();
    }

I get the exception at the lines where the object is serialized and deserialized.

Sarvavyapi
  • 810
  • 3
  • 23
  • 35
  • 1
    Is msgStruct an inner class? Java does not support serialization of non-static inner classes. If msgStruct is an inner class, try changing the access modifier to static. – rhoadster91 Oct 10 '13 at 17:07

1 Answers1

3

Is msgStruct an inner class by chance? If so, then try to make it static, or move it to its own java file.

bgse
  • 8,237
  • 2
  • 37
  • 39
  • bgse and @rhoadster91 - thanks. msgStruct was indeed an inner class and I moved it to its own java file. I no longer get the NotSerializableException. However, I am now getting - StreamCorruptedException. As per this thread - http://stackoverflow.com/questions/15733449/streamcorruptedexception-when-sending-serialized-objects-via-bluetooth, I initialize the output and the inputStreams just once when the socket is created. The client sends 4 messages and on the 4th msg it throws the StreamCorruptedException. The server on the other hand, receives only the 3rd msg. Is this a timing issue? – Sarvavyapi Oct 10 '13 at 17:41