DiskLruCache没有从key获取位图

时间:2014-07-01 20:07:20

标签: android bitmap android-asynctask

我正在使用JakeWhartons DiskLruCache和SO中的帖子中的一些代码。我可以使用键添加位图但无法在getBitmap()中检索它,而是返回null。我每次都要创建一个新的缓存吗?对此不确定。这是我的代码:

的AsyncTask:

public BitmapWorkerAsyncTask(ImageView imageView,Context context1) {

    imageViewReference = new WeakReference<ImageView>(imageView);
    diskLruCache = new DiskLruImageCache(context1, "thumbnails",
            (int) (20 * Math.pow(2, 20)), CompressFormat.JPEG, 70);
}

// Decode image in background.
@Override
protected Bitmap doInBackground(Object... params) {
    // Get the passed arguments here
    view = (View) params[0];
    songId = (Long) params[1];
    albumId = (Long) params[2];
    context = (Context) params[3];
    data = (Long) params[2];


    // Check disk cache
    Bitmap bitmap = diskLruCache.getBitmap(String.valueOf(albumId)); // returns null
}

DiskLruImageCache:

 public DiskLruImageCache(Context context, String uniqueName,
        int diskCacheSize, CompressFormat compressFormat, int quality) {
    try {
        final File diskCacheDir = getDiskCacheDir(context, uniqueName);
        // Log.d(TAG, "file cache dir="+diskCacheDir.getAbsolutePath());
        mDiskCache = DiskLruCache.open(diskCacheDir, APP_VERSION,
                VALUE_COUNT, diskCacheSize);
        mCompressFormat = compressFormat;
        mCompressQuality = quality;
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void put(String key, Bitmap data) {

    DiskLruCache.Editor editor = null;
    try {
        editor = mDiskCache.edit(key);
        if (editor == null) {
            return;
        }

        if (writeBitmapToFile(data, editor)) {
            mDiskCache.flush();
            editor.commit();
            if (BuildConfig.DEBUG) {
                Log.d("cache_test_DISK_", "image put on disk cache " + key
                        + "size aft adding=" + mDiskCache.get(key));
            }
        } 
}

public Bitmap getBitmap(String key) {

    Bitmap bitmap = null;
    DiskLruCache.Snapshot snapshot = null;
    try {
        Log.d("cache_test_DISK_", "bitmap got=" + mDiskCache.get(key)
                + " key=" + key);
        snapshot = mDiskCache.get(key); // null here
        if (snapshot == null) {
            return null;
        }
}

0 个答案:

没有答案