0

I have a fragment that contains a simple viewpager which uses a fragmentStatePagerAdapter.

When the user clicks on an item in a listview, the fragment mentioned above gets created and becomes visible. In the viewpager the fragment has, there's an imageview that contains a bitmap.

I get the error "RuntimeException :Trying to reuse recycled bitmap" when i use the back button to go to the listactivity again and select the same item (fragment) again. at this momement I can see logs in the application output from the ondestroy method

This is really strange cause I recycle the bitmap only in the onDestroy method from the fragment. So I wonder why i have this exception even though a viewpager fragment is created each time i pick an item in the list and when i push the back button the ondestroy gets called.

The method that gets called when an image is downloaded from the internet contains this snippet:

result = Bitmap.CreateBitmap (maskDrawable.IntrinsicWidth, maskDrawable.IntrinsicHeight, Bitmap.Config.Argb8888);
Paint paint = new Paint ();
paint.SetXfermode (new PorterDuffXfermode (PorterDuff.Mode.SrcAtop));
Canvas canvas = new Canvas (result);
if(canvas != null && mask !=null && scaledBitmap != null && result != null)
{
    canvas.DrawBitmap (mask, 0, 0, null); //error here
    canvas.DrawBitmap (scaledBitmap, 0, 0, paint);
}
if (imageBackground != null && activity != null) 
{
        activity.RunOnUiThread (() => imageView.SetImageBitmap(result));
}

the onDestroy method from the viewpager fragment:

public override void OnDestroy ()
{
        Console.WriteLine ("ondestroy viewpagerfragment");
        base.OnDestroy ();
        if (infoBtn != null)
        {
            infoBtn.Click -= ShowInfoDialog;
        }
        FileDownloader.DownloadCompletedEvent -= HandleDownloadCompletedEvent;
        imageView.SetImageBitmap(null);

        if (result != null) 
        {
            Console.WriteLine ("result RECYCLED");
            result.Recycle ();
            result = null;
        }
        if (drug != null) 
        {
            drug.Recycle ();
            drug = null;
        }
        if (mask != null) 
        {
            mask.Recycle ();
            mask = null;
        }
    }
DennisVA
  • 2,068
  • 1
  • 25
  • 35
  • Don't guess at how to handle bitmaps - https://developer.android.com/training/displaying-bitmaps/manage-memory.html – Simon Feb 28 '15 at 16:40
  • c'mon i read alot about bitmaps it is pointless. i'm just trying to create a new bitmap instance each time but it says it's recycled even though it's another and new bitmap object.. – DennisVA Feb 28 '15 at 16:48

1 Answers1

0

Re-using Bitmaps is tricky. In my experience you can either recycle them and call the GarbageCollector straight away to get the memory used by the Bitmap back or try to keep all of the ImageViews ready when you get into the Activity which uses them and then recycle their Bitmaps when you leave it.

JakeP
  • 1,736
  • 4
  • 23
  • 31