How to pass a List of Bitmaps effectively from an Activity to an other?

Amine :

I have a List of 3 Mat Opencv objects, I need to pass this list from an activity to an other in Android.

I have no clue how to share this List of Mats between activities, so I converted those Mat objects to Bitmaps and now I have to deal with Bitmaps.

I know that Bitmap class implements Parcelable by default so I used putParcelableArrayList like this

Intent intent = new Intent(InputProcessingActivity.this, CompareActivity.class);
intent.putParcelableArrayListExtra("", mats);
startActivity(intent);

But my Application just become dark and stays that way, I think this is happening because Bitmap objects are too large.

Can you suggest a solution to make this happen ?

92AlanC :

If it's something you intend to persist only at runtime I'd suggest you to store that list in a singleton object and then read from it on your next activity.

It's a pretty easy, straightforward and CPU/IO-friendly way to solve your problem.

Example:

public class BitmapDTO {

    private static BitmapDTO instance;

    public static BitmapDTO getInstance() {
        if (instance == null)
            instance = new BitmapDTO();
        return instance;
    }

    private List<Bitmap> bitmaps;

    private BitmapDTO() { }

    public void setBitmaps(List<Bitmap> bitmaps) {
        this.bitmaps = bitmaps;
    }

    public List<Bitmap> getBitmaps() {
        return bitmaps;
    }

}

Source activity:

BitmapDTO.getInstance().setBitmaps(myBitmaps);
Intent intent = new Intent(InputProcessingActivity.this, CompareActivity.class);
startActivity(intent);

And finally, on your target activity:

private List<Bitmap> myBitmaps;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_layout);
    myBitmaps = BitmapDTO.getInstance().getBitmaps();
    // Do your stuff
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=128957&siteId=1