Sebastian Engel
Sebastian Engel

Reputation: 3695

Bitmap.recycle() - "IllegalArgumentException: Cannot draw recycled bitmaps"

In the documentation, titled "Managing Bitmap Memory" you can find the following statement:

Caution: You should use recycle() only when you are sure that the bitmap is no longer being used. If you call recycle() and later attempt to draw the bitmap, you will get the error: "Canvas: trying to use a recycled bitmap".

So, what exactly means "no longer"?

I call setImageDrawable(drawable) in my fragments onCreateView(...) method. And I call recycle() on the drawable's bitmap in the fragment's onStop(). When the user now leaves the fragment by launching another activity the bitmap is recycled. But when the user comes back to the previous fragment, its onCreateView() is called again, resulting in a new call to "setImageDrawable(drawable)". And this throws:

IllegalArgumentException: Cannot draw recycled bitmaps

So, I still seem to be in the "no longer" context. When do I get a new bitmap, which is not recycled? Only after the fragment and its activity have been completely destroyed?

Upvotes: 2

Views: 2457

Answers (1)

T_V
T_V

Reputation: 17580

So, what exactly means "no longer"?

No longer means you are not going to use the same reference of Bitmap.

As you told you are recycling bitmaps on onstop(), try with this also inside your onStop()

   if(bitmap!=null)
   {
      bitmap.recycle();
      bitmap=null;
   }

Bitmap and outOfMemory in android

Watch first 20 minuts of this official video if you want to make your day good - http://www.youtube.com/watch?v=_CruQY55HOk

Upvotes: 2

Related Questions