Friday, June 5, 2020

Pass Bitmap Data Between Activities in Android

Pass Bitmap Data Between Activities in Android

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.
Pass Bitmap Data Between Activities in Android

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);

No comments:

Post a Comment