I hava a Bitmap variable named bmp
in Activity1 , and I want to send the bitmap to Activity2
Following is the code I use to pass it with the intent.
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image",bmp);
startActivity(in1);
And in Activity2 I try to access the bitmap using the following code
Bundle ex = getIntent().getExtras();
Bitmap bmp2 = ex.getParceable("image");
ImageView result = (ImageView)findViewById(R.Id.imageView1);
result.setImageBitmap(bmp);
The application runs without an exception but it does not give the expected result
We can also solve this without passing data through intent. Just store the image in the memory and in the next Activity just load the image from that location, which can also avoid app crash from passing large bitmap data. Note: You need not even pass the location path to the intent, remember the path and use it.
Simply we can pass only Uri of the Bitmap instead of passing Bitmap object. If Bitmap object is Big, that will cause memory issue.
FirstActivity.
From SecondActivity we get back bitmap.
Convert it to a Byte array before you add it to the intent, send it out, and decode.
Then in Activity 2:
edit
Thought I should update this with best practice:
In your first activity, you should save the Bitmap to disk then load it up in the next activity. Make sure to recycle your bitmap in the first activity to prime it for garbage collection:
Activity 1:
In Activity 2, load up the bitmap:
Cheers!
I would like to also post a best practices answer for those looking to do this (but may be asking the wrong question).
Instead of passing a bitmap around (which I presume you downloaded from the network, otherwise, you would already have a file reference to it), I recommend using an image loader such as Universal Image Loader to download an image into an ImageView. You can configure it to then cache the image to disk:
Now, just pass the image URL in your intent and use the UIL to load the image. In your newly created activity for example, the image will load instantly because it is loading from the cache - even if your image URL has expired since the download.
Sometimes, the bitmap might be too large for encode&decode or pass as a byte array in the intent. This can cause either OOM or a bad UI experience.
I suggest to consider putting the bitmap into a static variable of the new activity (the one that uses it) which will carefully be null when you no longer need it (meaning in onDestroy but only if "isChangingConfigurations" returns false).