Richard Suarez
Richard Suarez

Reputation: 119

How to pass a ArrayList<Bitmap> between activities

I have an ArrayList<Bitmap> that I have populated using the method getBitmapFromAsset() and want to pass it via intent using a Bundle. However it allows me to pass other ArrayLists like ArrayList<String> using:

Intent intent = new Intent(myClass.this, Rclass.class);  
Bundle bundle = new Bundle();    
bundle.putStringArrayList("names", (ArrayList<String>) names);  
intent.putExtras(bundle);
startActivity(intent);

But I don't know how to pass an ArrayList of the type Bitmap as I don't see that option in the Bundle. Any ideas of how to perform this?

Upvotes: 2

Views: 5810

Answers (2)

azgolfer
azgolfer

Reputation: 15137

Passing the bitmaps itself from one activity to another is very memory inefficient. It may be OK if your bitmaps are small size icons, but if they are large bitmaps, you may encounter out of memory exception.

Have you consider refactor this a little bit, e.g. Use a singleton that has a HashMap of Bitmap ID (or asset name) to WeakReference of the bitmap itself. This singleton, let's call it BitmapHelper, will auto reload the bitmap from the asset, if it has not yet been loaded or has been freed by the garbage collector.

After your have this BitmapHelper, then it's a matter of passing the bitmap id/asset name in a String Array to another activity. From the other activity, you could just access the bitmap from the BitmapHelper.

Upvotes: 7

yorkw
yorkw

Reputation: 41126

Bitmap implements Parcelable by default.

Use Bundle.putParcelableArrayList(String key, ArrayList<? extends Parcelable> value):

ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
bitmaps.add(bitmap);
bundle.putParcelableArrayList("names", bitmaps);

Upvotes: 3

Related Questions