Skip to content Skip to sidebar Skip to footer

How To Fix "canvas: Trying To Use A Recycled Bitmap Error"?

I'm creating a RecyclerView to show a Grid of pictures. When selecting one of them, it should open a new activity with a transition. I'm using Glide library to load the pictures an

Solution 1:

I suspect that once in a while your bitmap gets into the recycled state just before the Canvas gets a chance to draw onto it here drawable.draw(canvas);.

A quick solution should be not to call bitmap.recycle();, which is not strictly required for android >2.3.3. If you still want to reclaim this memory forcefully, you'll have to find a way to check when the bitmap is indeed no longer needed (i.e., Canvas had a chance to finish its drawing operations).

Solution 2:

Move bitmap.recycle(); to another place in the code where this bitmap is really no longer needed.

Solution 3:

Use this custom ImageView class

publicclassMyImageViewextendsImageView {
 
    publicMyImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
 
    publicMyImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
    publicMyImageView(Context context) {
        super(context);
    }
 
    @OverrideprotectedvoidonDraw(Canvas canvas) {
        try {
            super.onDraw(canvas);
        } catch (Exception e) {
            Log.i(MyImageView.class.getSimpleName(), "Catch Canvas: trying to use a recycled bitmap");
        }
    }
 
}

Solution 4:

I don't know much about canvas (I don't use animations that often) but if you don't find any way to fix this, you could try using this library instead: https://github.com/codepath/android_guides/wiki/shared-element-activity-transition

Solution 5:

I solved by adding this:

Glide.with(activity).clear(view);

before load the image:

Glide.with(activity)
                .load(imageUrl)
                .apply(options)
                .placeholder(R.drawable.loading_image)
                .error(R.drawable.not_found)
                .into(view);

See docs:

http://bumptech.github.io/glide/doc/resourcereuse.html

http://bumptech.github.io/glide/doc/resourcereuse.html#cannot-draw-a-recycled-bitmap

Post a Comment for "How To Fix "canvas: Trying To Use A Recycled Bitmap Error"?"