I am trying follow this answer to cache the bitmaps that I need to display in a listview. But there is no mentioning anywhere on how to use it in a class. Can anyone give me a sample code on how to use the DiskLruImageCache
in a class?
EDIT
This is what I tried. I have many activities, so I am using a singleton class named Model
. I created instance of DiskLruImageCache
inside model class and on the onCreate of the first activity I initialise the object like this:
private DiskLruImageCache diskLruImageCache;
public void prepareCache(Context context) {
diskLruImageCache = new DiskLruImageCache(context, "myappcache", 10, CompressFormat.JPEG, 100);
}
Then I have these two methods in the Model
class to store and get the bitmaps:
public void storeBitmapToCache(String key, Bitmap bitmap) {
diskLruImageCache.put(key, bitmap);
}
public Bitmap getBitmapFromCache(String key) {
return diskLruImageCache. getBitmap(key);
}
Then in a class I need to store an image, I do:
Model.getInstance().storeBitmapToCache("mykey",bitmap); //Model.getInstance() gets the current instance of the singletonclass
And to get it I use:
Model.getInstance().getBitmapFromCache("mykey");
But I was not getting the bitmap. Then I tried debugging and figured out that the image is getting stored in the cache, since the following is getting executed in DiskLruImageCache.java
when I try to save the bitmap.
if( writeBitmapToFile( data, editor ) ) {
mDiskCache.flush();
editor.commit();
if ( BuildConfig.DEBUG ) {
Log.d( "cache_test_DISK_", "image put on disk cache " + key ); //this line is getting printed
}
}
Which means the image is cached. But when I tried to get the bitmap, the following is getting executed in DiskLruImageCache.java
snapshot = mDiskCache.get( key );
if ( snapshot == null ) {
return null; //it is null and so is returning here
}
//hence the following which actually gets the bitmap fro cache is never getting executed.
final InputStream in = snapshot.getInputStream( 0 );
if ( in != null ) {
final BufferedInputStream buffIn =
new BufferedInputStream( in, Utils.IO_BUFFER_SIZE );
bitmap = BitmapFactory.decodeStream( buffIn );
}
And then I checked to see if the key "mykey"
which I used to store the bitmap is there in the cache by using the containsKey(String key)
method in DiskLruImageCache.java
, but it also returns a false. That is even the key I used to store the bitmap is not there and it IS getting stored. Is it any problem with what I am doing? Because I found out that lots of people are getting it working correctly from the answer. What am I doing wrong here? How to rectify this?