Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To: Parcel a bitmap in Android

I have a serialized class which I want to add a bitmap to, but Bitmap doesn't support serialize.

Instead I thought I'd use a parcel instead, but can't get it to work.

Here's some test code using local variables:

    Parcel parcel;
    Bitmap sourceBitmap;
    Bitmap destinationBitmap;
    parcel = Parcel.obtain();

    sourceBitmap = Bitmap.createBitmap(200, 400, Config.ARGB_8888);

    sourceBitmap.writeToParcel(parcel, 0);

    destinationBitmap = Bitmap.CREATOR.createFromParcel(parcel);

I get the following error on the last line above:

09-06 21:18:20.463: DEBUG/skia(17716): Bitmap_createFromParcel unknown config: 0
09-06 21:18:20.473: DEBUG/AndroidRuntime(17716): Shutting down VM
09-06 21:18:20.483: WARN/dalvikvm(17716): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
09-06 21:18:20.493: ERROR/AndroidRuntime(17716): Uncaught handler: thread main exiting due to uncaught exception
09-06 21:18:20.513: ERROR/AndroidRuntime(17716): java.lang.RuntimeException: Failed to unparcel Bitmap
09-06 21:18:20.513: ERROR/AndroidRuntime(17716):     at android.graphics.Bitmap$1.createFromParcel(Bitmap.java:899)
09-06 21:18:20.513: ERROR/AndroidRuntime(17716):     at android.graphics.Bitmap$1.createFromParcel(Bitmap.java:903)
like image 951
FrinkTheBrave Avatar asked Sep 06 '11 21:09

FrinkTheBrave


Video Answer


2 Answers

you have to reset your parcel:

sourceBitmap.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
destinationBitmap = Bitmap.CREATOR.createFromParcel(parcel);
like image 92
njzk2 Avatar answered Oct 03 '22 21:10

njzk2


Bitmap has already pacelled by android

http://developer.android.com/reference/android/graphics/Bitmap.html#writeToParcel(android.os.Parcel, int)

like image 32
waychow Avatar answered Oct 03 '22 22:10

waychow