How to avoid OutOfMemory (OOM) Exception using Bitmaps (Solved)


SDK Version: 
M3

Step 1.
First thing I want you to think about is that do You really need to use Bitmaps?
If the answer is No, go to step 2. :) Otherwise, think again.
Ok, Let me explain it. I needed Bitmaps to get the width of the images, to create an ImageAdapter for my Gallery. As far as I know, there's no other way to do that. So I used Bitmaps, and even if I recycled them, once in a while it stopped with the message: DDMS: OutOfMemory .. Phone: Force Close..
Not to speak about how laggy your app will be if you are using Bitmaps..
I've spent 2 weeks to find a solution for this problem, but I couldn't find any usable of them. Then I thought, I try not using Bitmaps anymore. So I have to find another way to get the width of images. Unfortunately, it's just a workaround, but it works so who cares, right?
I can determine widths with a PHP script, store it in my existing database. After I did that, everything was working properly.
Again, You really have to think about whether you really need Bitmaps or not.

Step 2.
I already told you what the solution is, but let see a working example. Let say we have an image Gallery, and in the ImageAdapter, what I'd like to do is:

  1. public ImageAdapter(Context c, List<Device> list) {
  2.         this.list = list;
  3.         mContext = c;
  4.         for (Device device : list) {  
  5.         ImageView tmp = new ImageView(mContext.getApplicationContext());
  6.         tmp.setImageURI(device.getFrontUri());
  7.         tmp.setLayoutParams(new Gallery.LayoutParams( (int)(device.getFrontWidth()), 345));
  8.                 tmp.setScaleType(ImageView.ScaleType.FIT_XY);
  9.                 tmp.setBackgroundResource(mGalleryItemBackground);
  10.                 imageList.add(tmp);
  11.         }
  12.     }

Of course this is just code snippet, but the point is that we didn't use any Bitmaps, just an ImageView, with URI.