0

I'm having a problem with OOM errors in my activities. I have a layout which uses two imageviews and a about 5 or 6 buttons. Currently, I get an OOM error but noted improvement with these methods. I use this method to setup my layout in the homescreen:

private void createButtons() 
{
    bitmaps = new ArrayList<Bitmap>();

    ImageView img = (ImageView)findViewById(R.id.homescreen_logo);
    Bitmap bmp = (Bitmap)BitmapFactory.decodeResource(getResources(), R.drawable.homescreen_logo);
    img.setImageBitmap(bmp);
    bitmaps.add(bmp);

    ImageView imge = (ImageView)findViewById(R.id.countdown_labels);
    Bitmap bitmp = (Bitmap)BitmapFactory.decodeResource(getResources(), R.drawable.homescreen_countdown_text);
    imge.setImageBitmap(bitmp);
    bitmaps.add(bitmp);
}

then, in the onPause method I call this method:

private void recycleHomescreenImages() {
    for (Bitmap bmap : bitmaps) {
        bmap.recycle();
    }
    bitmaps = null;
}

While this does lower my heap usage upon exiting the homescreen activity, it is not enough. Since the other views I use are not ImageViews, I can't employ the same tactic of just using the setImageBitmap() method. Any suggestions on how I can also force the collection of backgrounds for a button? Here's what one of my buttons look like in xml.

<Button
  android:id="@+id/1_button"
  android:layout_width="294dp"
  android:layout_height="60dp"
  android:layout_alignParentTop="true"
  android:layout_centerHorizontal="true"
  android:layout_marginTop="33dp"
  android:background="@drawable/homescreen_button_1"
  android:onClick="onClick1"/>

Thanks for any help.

user1132897
  • 1,201
  • 1
  • 14
  • 27

2 Answers2

1

I would recommend to load lazily those Bitmap and Drawable objects, e.g. as late as possible, on demand. Also, when you don't need them anymore, set the references to those Bitmap and Drawable objects to null, and make sure you have no other references to those Bitmaps and Drawables, to make them eligible for garbage collection. Note that you can not know, when the garbage collector kicks in, so this is all you can do to save memory. Hopefully this will help you.

overbet13
  • 1,646
  • 1
  • 19
  • 36
0

I was actually just able to get it working by modifying the answer from here to look like this:

private void unbindDrawables(View view) {
    if (view.getBackground() != null) {
    view.getBackground().setCallback(null);
    view.setBackgroundDrawable(null);
    }
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
        unbindDrawables(((ViewGroup) view).getChildAt(i));
        }
    ((ViewGroup) view).removeAllViews();
    }
}

Edit: Lies, I still get the OOM sometimes.

Community
  • 1
  • 1
user1132897
  • 1,201
  • 1
  • 14
  • 27