How to pass drawable between activities

android iPhone picture android iPhone · Dec 6, 2011 · Viewed 46.6k times · Source

How can I pass an image, drawable type between activities?

I try this:

private Drawable imagen;

Bundle bundle = new Bundle();
bundle.putSerializable("imagen", (Serializable) unaReceta.getImagen());
Intent myIntent = new Intent(v.getContext(), Receta.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);

But it reports me an execption:

java.lang.ClassCastException: android.graphics.drawable.BitmapDrawable

Answer

user849998 picture user849998 · Dec 6, 2011

1) Passing in intent as extras

In the Activity A you decode your image and send it via intent:

  • Using this method (extras) image is passed in 162 milliseconds time interval
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);     
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); 
byte[] b = baos.toByteArray();

Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("picture", b);
startActivity(intent);

In Activity B you receive intent with byte array (decoded picture) and apply it as source to ImageView:

Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("picture");

Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
ImageView image = (ImageView) findViewById(R.id.imageView1);

image.setImageBitmap(bmp);

2) Saving image file and passing its reference to another activity

"The size limit is: keep it as small as possible. Definitely don't put a bitmap in there unless it is no larger than an icon (32x32 or whatever).

  • In *Activity A* save the file (Internal Storage)
String fileName = "SomeName.png";
try {
    FileOutputStream fileOutStream = openFileOutput(fileName, MODE_PRIVATE);
    fileOutStream.write(b);  //b is byte array 
                             //(used if you have your picture downloaded
                             // from the *Web* or got it from the *devices camera*)
                             //otherwise this technique is useless
    fileOutStream.close();
} catch (IOException ioe) {
    ioe.printStackTrace();
}
  • Pass location as String to Activity B
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("picname", fileName);
  • In *Activity B* retrieve the file
Bundle extras = getIntent().getExtras();
String fileName = extras.getString("picname");
  • Make *drawable* out of the picture
File filePath = getFileStreamPath(fileName);
Drawable d = Drawable.createFromPath(filePath.toString());
  • Apply it to the ImageView resource
someImageView.setBackgroundDrawable(d);