Somesh Gupta
Somesh Gupta

Reputation: 287

When to recycle bitmap in android project?

I have successfully implemented lazy loading of list images and list items in Android listview. I am using Android 4.0+ and Java 7.

The algorithm i followed is:

  1. List data(including image URL) is downloaded from internet as and when user scrolls the list.

  2. When scroll state is idle, list images are loaded.

  3. In the background thread, images are first checked for in the cache. If not present in cache, they are downloaded and stored into the cache.

  4. Lastly image is set to imageview in the listview and adapter is notified.

The only problem is I am not clear about when to recycle bitmaps. I tried using bitmap.recyle() at many places but I got the following error:

java.lang.IllegalArgumentException: Cannot draw recycled bitmap

It is not possible to add that vast code over here. Also there are some privacy issues. Can someone please help me about this?

EDIT

My application size increases from 727 KB (at the time of installation) to 14 MB. After I recycle my bitmaps, in getView() of adapter I get "cannot generate texture from bitmap ". Can anyone suggest how to get rid of it?

Upvotes: 4

Views: 4044

Answers (3)

Nom1fan
Nom1fan

Reputation: 857

Bitmap recycling should be performed differently in different versions of Android. It is best to implement in a way that covers the majority of versions.

As others here said, recycle() renders your bitmap unusable, recycle() is meant to be used once you are finished with the bitmap and would like to induce a garbage collection. I think you should use it on your activity onPause()/onStop().

See here for more information: Managing Bitmap Memory

Upvotes: 0

kabuko
kabuko

Reputation: 36302

Recycling a bitmap renders it unusable. Only recycle when you're completely done with it. In your case, that means after it's been evicted from the cache. You'll also want to make sure that none of your existing views reference it.

Upvotes: 2

JRomero
JRomero

Reputation: 4868

As of ICS the need to recycle isn't necessary. There are a few instance where you would want to but considering most listview implementations it probably won't be necessary.

You can check out this video by Chet Hasse for more info on reusing bitmaps which would be better if they are the same size. DevBytes: Bitmap Allocation

Upvotes: 0

Related Questions