I have a Serialized class that I need to send as an object via Bluetooth, and also implements Runnable. As such, I set a few variables first, then send it as an object to be executed by another Android device, which will then set its result into a variable, and send back the same object with the result in one of the variables. I have been using the following two methods to serialize my object and get a ByteArray before sending them through the OutputStream of my BluetoothSocket, and to deserialize that ByteArray to get back my object.
public static byte[] serializeObject(Object o) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o);
out.flush();
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
}
public static Object deserializeObject(byte[] b) throws OptionalDataException, ClassNotFoundException, IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(b);
ObjectInputStream in = new ObjectInputStream(bis);
Object object = in.readObject();
in.close();
return object;
}
I still got the same error from these two methods, so I tried to merge it with the methods I use to send my ByteArray via BluetoothSocket's OutputStream, as shown below.
public void sendObject(Object obj) throws IOException{
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
ObjectOutputStream out = new ObjectOutputStream( bos );
out.writeObject(obj);
out.flush();
out.close();
byte[] buf = bos.toByteArray();
sendByteArray(buf);
}
public void sendByteArray(byte[] buffer, int offset, int count) throws IOException{
bluetoothSocket.getOutputStream().write(buffer, offset, count);
}
public Object getObject() throws IOException, ClassNotFoundException{
byte[] buffer = new byte[10240];
Object obj = null;
if(bluetoothSocket.getInputStream().available() > 0){
bluetoothSocket.getInputStream().read(buffer);
ByteArrayInputStream b = new ByteArrayInputStream(buffer);
ObjectInputStream o = new ObjectInputStream(b);
obj = o.readObject();
}
return obj;
}
In the end, I get the same error when deserializing the object at the receiving device, as shown below.
java.io.StreamCorruptedException
at java.io.ObjectInputStream.readStreamHeader (ObjectInputStream.java:2102)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:372)
and so on...
Can anybody please help? I'm desperate, this has been killing me for weeks, and I need this to work in a few days. :S
According to this and this thread :
You should use single
ObjectOutputStream
andObjectInputStream
for the life of the socket, and don't use any other streams on the socket.Secondly, use
ObjectOutputStream.reset()
to clear previous values.Let me know if this works !