views:

5492

answers:

2

Hi

I developed an application that uses lots of images on android.

The app runs once, fills the information on the screen (Layouts, Listviews, Textviews, ImageViews, etc) and user reads the information. There is no animation, no special effects or anything that can fill the memory. Sometimes the drawables can change. Some are android resources and some are files saved in a folder in the SDCARD.

Then the user quits (the onDestroy method is exectuted and app stays in memory by the VM ) and then at some point the user enters again.

Each time the user enters to the app, I can see the memory growing more and more until user gets the java.lang.OutOfMemoryError.

So what is the best/correct way to handle many images?

Should I put them in static methods so they are not loaded all the time? Do I have to clean the layout or the images used in the layout in a special way?

Thanks

Daniel

+2  A: 

It sounds like you have a memory leak. The problem isn't handling many images, it's that your images aren't getting deallocated when your activity is destroyed.

It's difficult to say why this is without looking at your code. However, this article has some tips that might help:

http://developer.android.com/resources/articles/avoiding-memory-leaks.html

In particular, using static variables is likely to make things worse, not better. You might need to add code that removes callbacks when your application redraws -- but again, there's not enough information here to say for sure.

Trevor Johns
this is true and also having lots of images (and not a memory leak) can cause outOfMemory for multiple reasons like lots of other apps are running, fragmentation of memory, etc.I learned that when working with lots of images if you get the outOfMemory systematically, like doing always the same, then its a leak. If you get it like once a day or something, its because you are too close to the limit. My suggestion in this case is try to remove some stuff and try again. Also Image memory is outside Heap memory, so look out for both.
Daniel Benedykt
A: 

I've ran into this exact problem. The heap is pretty small so these images can get out of control rather quickly in regards to memory. One way is to give the garbage collector a hint to collect memory on a bitmap by calling its recycle method.

Also, the onDestroy method is not guaranteed to get called. You may want to move this logic/clean up into the onPause activity. Check out the Activity Lifecycle diagram/table on this page for more info.

Donn Felker
Thanks for the info.I am managing all Drawables and not Bitmaps, so I cant call Recycle.Any other suggestion for drawables?ThanksDaniel
Daniel Benedykt