Harshit
Harshit

Reputation: 11

how to prevent out of memory error in android

I am new on android and I am developing an application in which I am downloading images from server in drawable array. Everything is right but when the activity(in which drawables are downloade one by one in thread) loads, after some time it gives out of memory error.

Please help.

Upvotes: 1

Views: 3661

Answers (2)

Joseph Earl
Joseph Earl

Reputation: 23432

  1. It's not a memory leak you have, you're simply trying to put more images into memory at once than will fit
  2. In order to solve that you can either
    • Use an array of SoftReference<Drawable>, store each drawable in the array as new SoftReference(myDrawable). When retrieving a SoftReference, check that SoftReference.get() is not null. If it is null the drawable has been reclaimed by the Garbage Collector (GC) and you will need to re-download it to memory, if it is not null then SoftReference.get() returns the drawable you stored in the SoftReference.
    • Limit the size of the array to an amount that will fit in memory. You will have to implement some system of storing new images over the older ones if the array has got to it;s maximum size (e.g. place the new image on the end of the array and remove the first element of the array)

SoftReferences allow the GC to reclaim the memory taken up by objects when low memory situations are encountered.

Upvotes: 1

Buda Gavril
Buda Gavril

Reputation: 21627

try to use streams instead loading it at once and use SoftReference. and read http://davidjhinson.wordpress.com/2010/05/19/scarce-commodities-google-android-memory-and-bitmaps/

Upvotes: 1

Related Questions