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.
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;
}
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With