Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 778
ahodder Avatar asked Dec 12 '25 18:12

ahodder


2 Answers

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;
}
like image 117
aroth Avatar answered Dec 14 '25 08:12

aroth


The question mentions Parcelable, which is not always Serializable. I think the right approach would be to write Parcelable to Parcel. Then use Parcel's marshall() method to write raw bytes out.

I played a little with it. If your Parcelable follows the protocol, following code writes out correct byte array for Parcelable. Assume that MyParcelable contains 2 strings and one int.

            Parcel parcel1 = Parcel.obtain();
            MyParcelable parcelable1 = new MyParcelable("a", "b", 25);
            parcelable1.writeToParcel(parcel1, 0);

            byte content[] = parcel1.marshall();
            parcel1.recycle();
            Parcel parcel2 = Parcel.obtain();
            parcel2.unmarshall(content, 0, content.length);
            parcel2.setDataPosition(0);
            MyParcelable parcelable2 = MyParcelable.CREATOR.createFromParcel(parcel2);
            parcel2.recycle();
            Toast.makeText(context, parcelable2.a + " " + parcelable2.b + " " + parcelable2.val, Toast.LENGTH_LONG).show();

Also see How to use Parcel in Android?

like image 45
Alex Gitelman Avatar answered Dec 14 '25 06:12

Alex Gitelman