2

in my app i change the resource of an ImageView a lot of times with this method:

private void setIcon(int id, int imageSource) {
    ((ImageView)findViewById(id)).setBackgroundResource(imageSource);
}

After a while i get an OutOfMemoryException. Is there a better method to free the old resource (image) before i load the new one?

EDIT

private void setIcon(int id, int imageSource) {
    ImageView imageView = (ImageView)findViewById(id);
    Drawable bg= imageView.getBackground();

    if(bg != null && bg instanceof BitmapDrawable) {
         BitmapDrawable bitmapDrawable = (BitmapDrawable) bg;
         bitmapDrawable.getBitmap().recycle();
         if(D)Log.d(TAG, "recycled bitmap");
    }

    Bitmap bm = BitmapFactory.decodeResource(getResources(), imageSource);
    imageView.setImageBitmap(bm);

}
user2784676
  • 105
  • 1
  • 12
  • 1
    check this answer : http://stackoverflow.com/questions/13118005/android-background-image-memory-usage and check the comments. – Kosh Dec 04 '13 at 13:39

1 Answers1

0

Before setting the new background, try to clear the memory for the old one, like this:

Drawable bg = image.getBackground();
if(bg != null && bg instanceof BitmapDrawable) {
    BitmapDrawable bitmapDrawable = (BitmapDrawable) bg;
    bitmapDrawable.getBitmap().recycle();
}

Do you have specific reasons to set the backgroundResource? Can't you simply use image.setResource(). That way it is easier to obtain the bitmap and recycle it.

Edit: if you only want one image (no overlays or something) than this is easier (and how it's supposed to be):

ImageView image = (ImageView)findViewById(id);
image.setImageResource(imageSource);

Using bitmaps:

Bitmap bm = BitmapFactory.decodeResource(getResources(), id);
image.setImageBitmap(bm);
image.getDrawable(); // will return a BitmapDrawable
Jeffrey Klardie
  • 3,020
  • 1
  • 18
  • 23