I have a class where i have an Drawable
as an member.
This class i am using for sending data across activities as an Parcelable
extra.
For that i have extended the parceble, and implemented the required functions.
I am able to send the basic data types using read/write int/string.
But i am facing problem while marshaling the Drawable object.
For that i tried to convert the Drawable
to byte array
, but i am getting class cast Exceptions.
I am using following code to covert my Drawable to Byte array:
Bitmap bitmap = (Bitmap)((BitmapDrawable) mMyDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[]byteArray = stream.toByteArray();
out.writeInt(byteArray.length);
out.writeByteArray(byteArray);
And to convert byte array to Drawable i am using following code:
final int contentBytesLen = in.readInt();
byte[] contentBytes = new byte[contentBytesLen];
in.readByteArray(contentBytes);
mMyDrawable = new BitmapDrawable(BitmapFactory.decodeByteArray(contentBytes, 0, contentBytes.length));
When i run this i get Class cast exception.
How can we write/pass Drawable using the HashMap?
Is there any way by which we can pass Drawable in Parcel.
Thanks.
As you already convert Drawable to Bitmap in your code, why not use Bitmap as an member of your Parcelable class.
Bitmap implements Parcelable by default in API, by using Bitmap, you don't need to do anything special in your code and it will automatically handled by Parcel.
Or if you insist to use Drawable, implement your Parcelable as something like this:
public void writeToParcel(Parcel out, int flags) {
... ...
// Convert Drawable to Bitmap first:
Bitmap bitmap = (Bitmap)((BitmapDrawable) mMyDrawable).getBitmap();
// Serialize bitmap as Parcelable:
out.writeParcelable(bitmap, flags);
... ...
}
private Guide(Parcel in) {
... ...
// Deserialize Parcelable and cast to Bitmap first:
Bitmap bitmap = (Bitmap)in.readParcelable(getClass().getClassLoader());
// Convert Bitmap to Drawable:
mMyDrawable = new BitmapDrawable(bitmap);
... ...
}
Hope this helps.