Fork me on GitHub

Pass Bitmap Data Between Activities in Android

Posted on 15 March 2014
Under Blog
Tagged
Android
Pass Bitmap Data Between Activities in Android | Jay Rambhia’s Blog

I was making an application where I chose image file using browser intent and process it using OpenCV NDK. I decided to keep a different Activity for the OpenCV part and hence I had to pass the bitmap data from my main Activity to the OpenCV part activity. I had written an application before where I starting one intent from another activity. But I did not know how to pass arguments to the new activity. I looked up on Google and found out how to call another activity and then how to pass required data.

Start New Activity from Current Activity

    Intent anotherIntent = new Intent(this, anotherActivity.class);
    startActivity(anotherIntent);
    finish();

Start New Acticity from Current Activity With Passing Required Data

    Intent anotherIntent = new Intent(this, anotherActivity.class);
    anotherIntent.putExtra("key", "value");
    startActivity(anotherIntent);
    finish();

putExtra() method is used to send extra data from one activity to another.

Extract Data In Other Activity

    data = getIntent().getStringExtra("key");

getIntent() method returns the intent that started this activity.

getStringExtra() retrieves extended data from the intent.

Now, it turns out that it’s not possible to pass Bitmap as extended data. It needs to be converted to byteArray.

Pass Bitamp as Extended Data

    ByteArrayOutputStream bStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bStream);
    byte[] byteArray = bStream.toByteArray();

    Intent anotherIntent = new Intent(this, anotherActivity.class);
    anotherIntent.putExtra("image", byteArray);
    startActivity(anotherIntent);
    finish();

Retrieve Bitmap in Other Activity

    Bitmap bmp;

    byte[] byteArray = getIntent().getByteArrayExtra("image");
    bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

Detailed StackOverflow Answer

Well, that’s how I pass bitmap data between two activities. There are some better methods to do this such as passing fileURIs.

P.S. Working on Android now. Need to get better at layouts and designs.

If you liked - Pass Bitmap Data Between Activities in Android and found it helpful, please share it with your fellow developers.

comments powered by Disqus


If you have some feedback or questions regarding this post, please add comments. I'd be happy to get some feedback.



If you liked this post, then you should follow Jay on twitter too. He would be excited to know that you like his work.