How to avoid OutOfMemory Error / OOM (The Ugly Truth Revealed)


SDK Version: 
M3

ERROR/dalvikvm-heap(4204): 691456-byte external allocation too large for this process.
01-25 22:13:18.694: ERROR/(4204): VM won't let us allocate 691456 bytes 01-25 22:13:18.694

If you have ever got the message above, you are at the right place.

First of all the reason:
Heap size != External Memory size

Dalvik's external memory is limited to ~ 4MBs for each process (That is the Ugly Truth). If it overflows, you get the BitmapFactory.DecodeFile Error.
That's why even if you have like 2MB-s heap memory free, VM won't let you allocate ~700KB.
Since you can't modify external memory's size, you have to reduce your memory usage. This is the only solution I have, but it really works at least.

The solution:

Let say you have a nice big Gallery with lots of large images. An ImageAdapter class will provide all of the images that you are going to use. Therefore you'll need a List of ImageViews.
Now. Once you have set an ImageView, even if you're not using it, even if you call recycle() on Bitmap in it, it stays in that 4MB external memory. The only solution is not to use more ImageViews than 5 or maximum 10 at a time.

How can you do it? Well that's the tricky part. Probably you have to write an algorythm in your ImageAdapter Class for it, that can manage to free the ImageView-s you are not using, with calling the

  1. myImageView.setImageBitmap(null);

or if you are adventurous enough, :) can use a small "loading" image from Resource, while you don't have to show the original picture. But be careful, because this can also eat your 4MB memory if you use it wrong.
  1. myImageView.setImageResource(R.drawable.loadingImage);

Hope this helps, let me know what happens!