Out of Memory Error ImageView issue

To add on Ken’s answer, which is a solid piece of code, I thought I’d knock it down after he set it up:

    if(imageView != null) {
        ((BitmapDrawable)imageView.getDrawable()).getBitmap().recycle();
    }
    imageView = (ImageView) view.findViewById(R.id.imageView);
    imageView.setImageResource(resID);

NOTE: This won’t work if you are trying to swap an image you already recycled. You’ll get something like this in LOGCAT

Canvas: trying to use a recycled bitmap

So what I do now if I don’t have to load a bunch of different images asynchronously, I simply put this in onDestroy when dealing with fragments and large background images:

@Override
public void onDestroy() {
    super.onDestroy();

    imageView.setImageDrawable(null);
}

Leave a Comment