Java – Android tells me that my bitmap has been recycled before I actually recycle it
I get my bitmap from XML:
//Get bitmap from drawable bd = (BitmapDrawable) view.getResources().getDrawable(R.drawable.backgrounds); backgrounds = bd.getBitmap(); //Do required work with bitmap (Will just use a log statement here for testing Log.v("NewTag","Testing: "+bd.getBitmap().getPixel(0,0)); //Now recycle this large bitmap bd.getBitmap.recycle(); bd=null; backgrounds.recycle(); backgrounds=null;
The first time I ran this code, everything was fine However, when I exit my application (using the back key) and restart the application, it may or may not work Sometimes I get an error:
Why? I haven't recycled it yet Or rather, it doesn't seem to recreate the bitmap and remember the last recycle
This problem does not occur if I use bitmapfactory to get bitmaps (unfortunately, I can't do this because I have to get this special location map from an XML alias)
Before installing the lollipop, this works normally (as long as I have BD = null)
I've had this problem for two consecutive days, so if someone can shine on it, I'll be very grateful
edit
I tried @aga to advise against recycling / zeroing BD, but it makes no difference Once recreated (again, intermittently), the bitmap is still "recycled"
In addition, when so recorded:
Log.v("NewTag","Backgrounds: "+backgrounds);
I noticed that when it failed, the record reference was the same as the previous one So
Solution
The resources class has caches for resources loaded from your APK When you recycle drawable and bitmap, the cached objects will be destroyed The resource cache cannot know this, so the next time you request the resource, they will happily return the same object
When your application process terminates, all memory state will be lost, including the resource cache – so things will work again (once) Please note that "exiting" the application or destroying the activity does not necessarily mean that your process will die