Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass Drawable using Parcelable

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.

like image 723
User7723337 Avatar asked Apr 09 '12 08:04

User7723337


People also ask

How does Parcelable works in Android?

A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.


2 Answers

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.

like image 117
yorkw Avatar answered Oct 19 '22 15:10

yorkw


In my app, I saved Drawable/BitMap into Cache and passing it using file's path String instead.

Not a solution you were looking for, but at least some alternative for your problem.

like image 34
RobGThai Avatar answered Oct 19 '22 13:10

RobGThai