0

我正在尝试按照这个答案来缓存我需要在列表视图中显示的位图。但是没有任何地方提到如何在课堂上使用它。谁能给我一个关于如何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"使用 incontainsKey(String key)方法检查了用于存储位图的键是否在缓存中DiskLruImageCache.java,但它也返回 false。甚至我用来存储位图的密钥也不存在,它正在被存储。我在做什么有什么问题吗?因为我发现很多人都从答案中得到了正确的工作。我在这里做错了什么?如何纠正这种情况?

4

0 回答 0