0

I need to set a different background to layout based on some event. This was causing OOM exception. I added code to fix this but this is now causing recycled bitmap issue.

Here is the code:

       if (change_bg != 0) {
            //Garbage collect the current BG.
            BitmapDrawable bg = ((BitmapDrawable)llayout.getBackground()); 
            llayout.setBackgroundResource(0);
            if (bg != null) {
                bg.getBitmap().recycle();
                bg = null;
            }
            System.gc();

            llayout.setBackgroundResource(change_bg);
            llayout.invalidate();
        }

This does not happen the first time but after some 4-5 events randomly.

If I do not call bg.getBitmap().recycle, the OOM exception is encountered.

Can anyone point out the mistake or suggest the correct method to set the layout background in the same view?

Note:

  1. I removed the android:background="@drawable/bg_initial" in the ;ayout but it had no effect.

  2. The App is using other views with layouts having background image and the problem is not seen with those views.

Prima facie this does not seem to be memory issue but problem when setting a different background in the same view. I can implement a different to switch the background image but this seems overkill. Would be glad if someone offers a simple and real solution.

EDIT :

I added the background bitmap garbage collect code in OnDestroy() and that seems to have solved the issue.. atleast I am not able to recreate the problem now.

But I am wondering what is the explanation for this. I am not holding the layout or images in a static variable so I am not sure it was held in memory. I am wondering what is going on. Can someone explain this?

Mano
  • 314
  • 1
  • 5

1 Answers1

0

This might be because the imageView is referring to the image, and before you setting a new background image, you are recycling the previous image (which is still referred by the imageView), and hence its throwing the exception.

Try following:

  1. Get the previous background by BitmapDrawable bg = ((BitmapDrawable)llayout.getBackground());
  2. Now set new background
  3. Garbage collect the previous background.

Please see my answer to solve OOME, it might help you. bitmap size exceeds Vm budget error android

Community
  • 1
  • 1
Shrikant Ballal
  • 7,067
  • 7
  • 41
  • 61
  • If you read the code carefully, what you suggest is already being done. llayout.setBackgroundResource(0). And the recycled bitmap exception is thrown on the second call to setBackground. And I am not using a ImageView but setting the linear layout background. – Mano Feb 05 '13 at 14:15