Search code examples
javaandroidobjectarraysparcelable

How to break an object into a byte[]?


How do I break an object --- a Parcelable to be more specific; actually it's a bundle but the point is the same --- into a byte[]? I thought that the way I was doing it was a good solution but apparently I was mistaken.

Just for reference here is the old way I was doing it.

public static byte[] getBytes(Object obj) throws java.io.IOException {
    ByteArrayOutputStream bos   = new ByteArrayOutputStream();
    ObjectOutputStream oos      = new ObjectOutputStream(bos);
    oos.writeObject(obj);
    oos.flush();
    oos.close();
    bos.close();
    byte[] data = bos.toByteArray();
    return data;
}

Thanks ~Aedon

Edit 1::

Breaking an object like this passing a Bundle to it causes a NotSerializableException.


Solution

  • Your code looks mostly fine. I would suggest the following:

    public static byte[] getBytes(Serializable obj) throws IOException {
        ByteArrayOutputStream bos   = new ByteArrayOutputStream();
        ObjectOutputStream oos      = new ObjectOutputStream(bos);
        oos.writeObject(obj);
    
        byte[] data = bos.toByteArray();
    
        oos.close();
        return data;
    }