1

I have a AnimationDrawable that i initialise before starting the animation and recycle it right as it finishes.. the problem is that when i want to start the animation again, i reinitialise everything but still gives an exception

java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@2bbad018

here's my code

 public ImageView radarImageView;
 public AnimationDrawable animationDrawable;

    public void animationStart() {

//        animationStop();

        radarImageView = (ImageView) findViewById(R.id.radarIV);
        radarImageView.setBackgroundResource(R.drawable.sensor_animation);
        animationDrawable = (AnimationDrawable) radarImageView.getBackground();

        animationDrawable.start();
    }

    public void animationStop() {

        animationDrawable.stop();

        for (int i = 0; i < animationDrawable.getNumberOfFrames(); ++i){
            Drawable frame = animationDrawable.getFrame(i);
            if (frame instanceof BitmapDrawable) {
                ((BitmapDrawable)frame).getBitmap().recycle();
            }
            frame.setCallback(null);
        }
        animationDrawable.setCallback(null);

//        animationDrawable = null;
//        radarImageView.setBackgroundResource(0);
    }

Why does it not reinitialise the whole thing again?

Ahmed Z.
  • 2,329
  • 23
  • 52
  • Why do you need to recycle the bitmap? calling `animationDrawable.stop()` is not enough for you? – hoomi Sep 08 '15 at 17:46
  • stop() doesn't release the memory.. thats why i need to call recycel – Ahmed Z. Sep 08 '15 at 18:01
  • 1
    The problem is that because when you call recycle on the bitmap you cannot reuse it. and because you are calling `setBackgroundResources(R.drawable. sensor_animation)` you are referring to the same object which its bitmaps were recycled previously. You either have to create a new drawable every time or do not recycle the instace – hoomi Sep 08 '15 at 18:08
  • Thank you hoomi.. this is the only sensible answer i was able to find since 2 days,.. u saved my day bro – Ahmed Z. Sep 09 '15 at 08:05
  • 1
    No problem. Should I make it an answer so you can accept? – hoomi Sep 09 '15 at 08:37

1 Answers1

1

The problem is because when you Bitmap.recycle() is called on the bitmap you cannot reuse it.

Also as you are calling setBackgroundResources(R.drawable.sensor_animation) you are referring to the same object which its bitmaps were recycled previously.

As a solution, you either have to create a new drawable every time or do not recycle that instance.

If you are worries about the memory usage try to use smaller bitmaps. Also using the correct sizes for different screen densities would help.

hoomi
  • 1,882
  • 2
  • 16
  • 17