Search code examples
androidbitmapandroid-recyclerviewandroid-custom-view

OutOfMemory Exception Android load custom bitmap image in ImageView of RecyclerView


I have a RecyclerView which is showing a CardView. In the CardView there are two items:

  1. TextView
  2. My custom view with underlying bitmap

The bitmap is created dynamical.

After some up and down scrolling I get an OutOfMemoryException.

I'm not sure how to handle it? Should I use LRUCache? Or third party libraries like Picasso - which seems to only work on urls and ids?

Any help appreciated

Update:

public class ManageProfileAdapter : RecyclerView.Adapter
{
  public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
  {
    ManageProfileViewHolder vh = holder as ManageProfileViewHolder;

    vh.Caption.Text = profiles[position].Name;
    vh.Thumbnail.SetProfile(profiles[position].Profile);
  }
}

The thumbnail class is a custom class derived from View (which includes bitmap):

public class ThumbnailView : View
{
   private Canvas DrawCanvas;
   private Bitmap CanvasBitmap;
}

The bitmap is drawn on the Canvas.


Solution

  • This guided me in the right direction:

    You must be creating bitmap data somewhere in your code again and again. Check it out

    The bitmap in my thumnail view is not removed by the garbage collector.

    The solution is:

    1. Override the OnDestroyView event of your Fragment
    2. Call adapter.Dispose() inside it
    3. In your adapter add a List of your ViewHolderItems
    4. In the OnCreateViewHolder method add the ViewHolderItems to your List
    5. Override the Dispose method of your adapter
    6. In the Dispose method go through your list and dispose the bitmap of the ViewHolder
    7. Finally clear your ViewHolder list

    I got no memory exceptions anymore and in logcat my highest usage is 30mb ram.

    Lesson Learned: You have to dispose bitmaps yourself in RecyclerView

    Thank you very much.