Mazin Almaskari
Mazin Almaskari

Reputation: 123

Putting an image to a Bundle

How can I save an image captured by the camera in a bundle and move it to the second activity? Where am I doing wrong here?

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAM_REQUEST) {

        if (resultCode == RESULT_OK) {

            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");

            Intent i = new Intent(this, PostActivity.class);
            i.putExtra("name", thumbnail);
            startActivity(i);



        }
    }
}

Upvotes: 0

Views: 1600

Answers (2)

Konrad Krakowiak
Konrad Krakowiak

Reputation: 12365

There is a few way how to pass bitmap to second Activity

You can pass Bundle form Intent.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAM_REQUEST) {
            if (resultCode == RESULT_OK) {    
                Bundle extras =  data.getExtras()    
                Intent i = new Intent(this, PostActivity.class);
                i.putExtra("extras", extras);
                startActivity(i);
            }
     }
}

And in the PostActivity you can call

 Bundle extras = getIntent().getBundleExtra("extras")
 Bitmap thumbnail = (Bitmap) extras.get("data");

Or if you want to pass only image you have to convert Bitmap to byte array

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAM_REQUEST) {
                if (resultCode == RESULT_OK) {  
                    Intent intent = new Intent(this, PostActivity.class);
                    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    thumbnail.compress(Bitmap.CompressFormat.PNG, 100, stream);
                    byte[] byteArray = stream.toByteArray();
                   intent.putExtra("image",byteArray);
                   startActivity(i);
               }
          }
}

Or your method should also right. You have to get Bitmap by getParcelableExtra(String) method.

 Bitmap thumbnail = getIntent().getParcelableExtra("data");

Upvotes: 0

Cà phê đen
Cà phê đen

Reputation: 1951

Bitmap implements Parcelable, so you should use:

Bitmap thumbnail = (Bitmap) data.getParcelableExtra("data");

Upvotes: 1

Related Questions