Android - Memory leak when dynamically building UI with image resource backgrounds

Posted by Rich on Stack Overflow See other posts from Stack Overflow or by Rich
Published on 2011-01-10T20:47:30Z Indexed on 2011/01/10 20:54 UTC
Read the original article Hit count: 180

I have an Activity that I swear is leaking memory. The app I'm working on does a lot with images, so I've had to be pretty stingy with memory when working directly with Bitmaps. I added an Activity, and now if you use this new Activity it basically puts me over the edge with mem usage and I end up throwing the "Bitmap exceeds VM budget" exception. If you never launch this Activity, everything is smooth as it was previously.

I started reading about memory leaks, and I think that I have a similar situation to what is described in the article in the Android docs. I'm dynamically creating a bunch of image views and adding a BackgroundDrawable from the resources and adding an OnClickListener as well. I imagine I have to do some cleanup when the Activity hits onPause in its life cycle, but I'd like to know specifically what is the correct way.

Here is the code that should demonstrate the objects I'm working with...

    LinearLayout templateContainer;
    .
    .
    .
    ImageView imgTemplatePreview = (ImageView) item.findViewById(R.id.imgTemplatePreview);
    .
    .
    .
    imgTemplatePreview.setBackgroundDrawable(getResources().getDrawable(previewId));
    imgTemplatePreview.setOnClickListener(imgClick);
    templateContainer.addView(item); 

© Stack Overflow or respective owner

Related posts about java

Related posts about android