在类中使用DiskLruImageCache

时间:2014-08-11 14:44:20

标签: android bitmap android-lru-cache

我正在尝试按照this answer缓存我需要在列表视图中显示的位图。但是没有提到如何在课堂上使用它。任何人都可以给我一个关于如何在类中使用DiskLruImageCache的示例代码吗?

修改

这就是我尝试过的。我有很多活动,所以我使用的是名为Model的单例类。我在模型类中创建了DiskLruImageCache的实例,在第一个活动的onCreate上我初始化了这个对象:

private DiskLruImageCache diskLruImageCache;

public void prepareCache(Context context) {
    diskLruImageCache = new DiskLruImageCache(context, "myappcache", 10, CompressFormat.JPEG, 100);
}

然后我在Model类中有这两个方法来存储和获取位图:

public void storeBitmapToCache(String key, Bitmap bitmap) {
    diskLruImageCache.put(key, bitmap);
}

public Bitmap getBitmapFromCache(String key) {
    return diskLruImageCache. getBitmap(key);
}

然后在课堂上我需要存储图像,我这样做:

Model.getInstance().storeBitmapToCache("mykey",bitmap); //Model.getInstance() gets the current instance of the singletonclass

为了得到它,我使用:

Model.getInstance().getBitmapFromCache("mykey");

但我没有得到位图。然后我尝试调试并发现图像存储在缓存中,因为当我尝试保存位图时,DiskLruImageCache.java中会执行以下操作。

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
    }
}

这意味着图像被缓存。但是当我尝试获取位图时,以下内容将在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 );              
}

然后我通过"mykey"中的containsKey(String key)方法查看我用于存储位图的密钥DiskLruImageCache.java是否存在于缓存中,但它还返回了假。这甚至是我用来存储位图的关键不在那里而且它被存储了。我正在做的事情有什么问题吗?因为我发现许多人从答案中得到了正确的工作。我在这做错了什么?如何纠正这个?

0 个答案:

没有答案