I am using message api to send messages between a smart phone and a smart watch. As it can send only byte arrays as data, I would like to convert an object into byte array while sending and reverse the conversion while receiving.
I have used the below code which I got from internet. But I am getting java.io.NotSerializableException. Is there any better way to do it?
My object will have a string value and an android bundle. Both needs to be sent from one device and received at the other end.
public static byte[] toByteArray(Object obj) throws IOException {
byte[] bytes = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
} finally {
if (oos != null) {
oos.close();
}
if (bos != null) {
bos.close();
}
}
return bytes;
}
public static Event toObject(byte[] bytes) throws IOException, ClassNotFoundException {
Event obj = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
bis = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bis);
obj = (Event) ois.readObject();
} finally {
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
}
return obj;
}