How can I pass an image, drawable type between activities?
I try this:
private Drawable imagen;
Bundle bundle = new Bundle();
bundle.putSerializable("imagen", (Serializable) unaReceta.getImagen());
Intent myIntent = new Intent(v.getContext(), Receta.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
But it reports me an execption:
java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable
Drawable
objects are not inherently serializable, so they cannot be passed directly inIntent
extras. You must find another way to serialize or persist the image data and retrieve it in the new Activity.For example, if you are working with
BitmapDrawable
instances, the underlyingBitmap
could be written out to a file and read back, or serialized into a byte array (if its small enough) and the byte array could be passed via extras of anIntent
.HTH
1) Passing in intent as extras
In the Activity A you decode your image and send it via intent:
In Activity B you receive intent with byte array (decoded picture) and apply it as source to ImageView:
2) Saving image file and passing its reference to another activity
You can simply use a native
buildDrawingCache
method:then get it at your ImageActivity:
You can tag each image (in the xml, or programmaticlly) with the image resource name (like "img1.png"), then retrieve the image name using the
getTag();
Then use
getResources().getIdentifier(image name,"drawable", .getPackageName())
to get the drawable resource id.And just pass the resource id through the intent -
Lastly the result Activity can create the image from the resource using:
Much much much better not to pass (or serialize)
Drawables
around amongActivities
. Very likely your are getting the drawable out of a resource. Hence there's a resource ID. Pass that around instead, that's just an int. And re-hydrate theDrawable
in the otherActivity
.If the
Drawable
is not coming from a resource, but it's built at runtime in memory ... well let's speak about it. @Devunwired has a nice suggestion in that case.I don't know if this is the case, but if the reason why you are trying to pass a drawable is because you are using an Imageview, just put the resource id in the imageview's tag, pass the tag as an Integer instead of the drawable in the intent's extra and use the following line in the receiving activity: imageView.setImageDrawable(getResources().getDrawable(getIntent().getIntExtra("image_id",0)));
Hope it will help someone.