0

I have an activity with an empty ImageView and a button. After clicking the button, I display the device's media gallery, the user chooses an image that gets passed to the activity via an intent. I use the image's URI from the returned data and I populate the ImageView, like this:

private ImageView pic;

@Override
public void onCreate(Bundle savedInstanceState) 
{

      pic = (ImageView)findViewById(R.id.bbChildImage);

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{  

        if(resultCode == RESULT_OK)
        {   
            URI currImageURI = data.getData();
            pic.setImageURI(currImageURI);
        }
}

Now, if I go to choose another image from the gallery, after the data is returned, I get a bitmap related OutOfMemory exception.

I figured out two ways to get rid of it. I either do this before assigning the URI:

((BitmapDrawable)pic.getDrawable()).getBitmap().recycle();

or instead of assigning the URI to the view, I retrieve the bitmap first, and then assign it, like this:

Bitmap thumbnail = MediaStore.Images.Media.getBitmap(this.getContentResolver(), currImageURI);
pic.setImageBitmap(thumbnail);

I am not sure which one is better. Also, if there are better ways, I would appreciate the feedback.

Thanks.

EboMike
  • 76,846
  • 14
  • 164
  • 167
oviroa
  • 1,079
  • 2
  • 12
  • 29
  • It's the size of the image captured by the device's camera, so could be between 1 and 3 megs, depending on the device. – oviroa Aug 02 '11 at 04:53
  • your first approach is better – ingsaurabh Aug 02 '11 at 05:13
  • @ingsaurabh, can you explain why? – oviroa Aug 02 '11 at 05:21
  • 1
    because in second approach you are not freeing up the memory so sooner or later you will again get OOM Its always a good idea to recycle bitmap once you are done with that for more indo check this out http://stackoverflow.com/questions/6213690/outofmemory-error-while-joining-large-images – ingsaurabh Aug 02 '11 at 05:25

1 Answers1

1
  1. Recycling is typically the way to go. If you don't need a bitmap, let the operating system know by recycling it.

  2. In addition to that, I would use the BitmapFactory to create the bitmap and use the options to shrink it upon loading. Don't make it bigger than the device's screen. That will save a lot of memory.

EboMike
  • 76,846
  • 14
  • 164
  • 167
  • how would I make the Bitmap using BitmapFactory if the intent sent back a URI? – oviroa Aug 02 '11 at 05:23
  • 1
    Here are some examples: http://stackoverflow.com/questions/3879992/get-bitmap-from-an-uri-android – EboMike Aug 02 '11 at 05:32
  • Also, I can do that for display purposes only, but I still need the full bitmap because I need to upload it via a web service – oviroa Aug 02 '11 at 05:33