Cote Mounyo
Cote Mounyo

Reputation: 13965

Caching decoded bitmap already stored on file system

I am working on a number of small bitmaps, about 100 of them. But they are very small thumbnail sized images. My design is such that I download the list from the server and save them on the local file system. When a user needs a bitmap, I do

BitmapFactory.decodeFile(pathName);

My question basically is: should I cache the decoded bitmap? So that next time the call is made, instead of decoding it again, I can return the already decoded image. For some context, these bitmaps are used throughout my app, so calls to decode are frequent. But on the other hand, I would be caching about 100 bitmaps. So the new code would be

if(null == bitmap)
    return (bitmap = BitmapFactory.decodeFile(pathName));
else return bitmap;

Can someone please talk to the cost/benefit of the new design in terms of space/time complexity, performance, sound design, and such? Also the bitmaps are usually shown in a ListView.

Why the response from @dumazy is not obvious for my case:

When I download from server, I store metadata in a hashmap:

Map<String,MyIcon> myIcons …

and the MyIcons class is like this:

class MyIcon{

   String filepath;//path of image on local filesystem.
   String url;// url to where image is on server
   Bitmap myImage;// for caching so not to decode each time
   ...//other fields about the icon

//then a number of methods
}

So from my perspective, going with LruCache means creating a static nested class extending LruCache, inside MyIcon. Then for each instance of MyIcon, I would need to make sure the associated myImage is set to null when it's bitmap is evicted from the LruCache. This seems complicated and I am not even sure it would work. Maybe the Java experts here can tell me how to know if it's working should I implement it.

Upvotes: 0

Views: 171

Answers (1)

dumazy
dumazy

Reputation: 14435

Bitmap decoding takes quite some time. Best practice is using a LruCache. Check out this tutorial here

Since you are using a ListView for it, only load them in the getView() method of your Adapter. Also use an AsyncTask to load them initialy

Upvotes: 1

Related Questions