Saturday, October 29, 2011

Solution for Out Of Memory Error and recycled bitmap Exception


Using bitmapDrawable.getBitmap().recycle() may clear all the memory cached by your ImageView object and avoid the situation where Out Of Memory Error occurs, it is very useful while dealing with large images. Non proper usage of this method will cause  Exception: java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@405a8818.


Solution:
This exception occurs when you try to recycle a bitmap which is already recycled. You should not remove bitmap.recycle() function from your existing code, it may cause Out Of Memory Error. You can try this below code to fix the issue.

    BitmapDrawable bitmapDrawable = ((BitmapDrawable) profileWallpaper.getDrawable());
   
    if (null != bitmapDrawable && bitmapDrawable.getBitmap().isRecycled()) {
   
bitmapDrawable.getBitmap().recycle();
  } else {
   
log("bitmap is already recycled");
     }
   
      bitmapDrawable = null;

*Note: profileWallpaper is your imageView object*

2 comments:

  1. Is above condition you are checking correct ?
    if (null != bitmapDrawable && bitmapDrawable.getBitmap().isRecycled())

    if both are true you want bitmap to be RECYCLED. ?
    means If bitmap is already recycled you want this to be recycled again ?

    ReplyDelete
  2. are you sure, it does so as you expect ?

    ReplyDelete