views:

60

answers:

3

I have a bitmap that I load from the SD card by allowing the user to choose a picture to display. Once the bitmap is created, I set the Bitmap in an ImageView:

mBitmap = Bitmap.createBitmap(Media.getBitmap(this.getContentResolver(), mPictureUri));
mImageView.setImageBitmap(mBitmap);

This works fine. But, if I change the screen orientation from portrait to landscape, and back again a few times, I always get an OutOfMemory exception.

In onPause, I call mBitmap.recycle(), and then on onResume, I call the above code again to create the bitmap and set the ImageView. Since I'm recycling the image each time, how can I get an OutOfMemory error?

In any case, since that failed, I found a post that said to try using onRetainNonConfigurationInstance() and getLastNonConfigurationInstance(). See post http://stackoverflow.com/questions/3250987/save-cache-when-rotate-device/3252547#3252547. I changed my code to work this way, and I still get an error. Changing the code, I had the call to getLastNonConfigurationInstance() in onCreate(), and removed all code in onPause and onResume.

Can someone tell me what the problem is, or provide some way to simply load an image, and then be able to pause and resume the Activity without running out of memory? Thanks.

+1  A: 

Try reducing the size of your bitmap. How big is it? Use BitmapFactory.options. Also instead of using "this instance". See the article about memory leaks: http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html

Megha Joshi
A: 

Hi Megha (I could not sign into my account for some reason), after I wrote the above post last night, that's the exact thing that I tried next. Using BitmapFactory.options to reduce the size seems to have alleviated the problem.

I still am very curious as to why the memory leaks were still taking place. Unfortunately I can't access the memory-leak link you provided right now, so I'll have to take a look at that link as soon as I get home (and I'll mark your answer as accepted too).

Thanks for the suggestion.

Michael
A: 

The memory leaks could be due to holding on to the context instance which in turn contains references to all the objects from the Activity before it was destroyed. The article explains it better.

You should reduce size of the images because there is 16MB per app, if you have large bitmaps being recreated, they could accumulate to 16MB before they are garbage collected or if there are memory leaks.

Megha Joshi
Thanks again Megha, I've accepted your answer above. As I said earlier, using BitmapFactory.options solved the issue for me.
Michael