How to avoid an out of memory error while using bitmaps in Android

When you have done with your Bitmap, means when your Bitmap done its work then make it recyle and null like below:

bitmap.recycle();
bitmap=null;

OR

I think you are downloading Image from url, so I am suggesting you to use Android Query for this, you will never get this error if you used it.

You can download the jar file from here :
http://code.google.com/p/android-query/downloads/list
Download the jar file and set jar to your Build Path.

 AQuery androidAQuery=new AQuery(this);

As an example to load image directly from url:

androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);

As an example to get Bitmap from url:

androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
    @Override
    public void callback(String url, Bitmap object, AjaxStatus status) {
        super.callback(url, object, status);

        //You will get Bitmap from object.
    }
});

It’s very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.

Leave a Comment