位图正在保存到LruCache,但它们无法获得

时间:2014-09-03 17:05:10

标签: android android-lru-cache

我将GridView中的Bitmaps缓存到LruCache。我为此做了经理,见下文:

private LruCache<String, Bitmap> mMemoryCache;

public LruCacheManager(){
    init();
}

private void init(){

    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    //Log.i("ImageCache","cacheSize: " + cacheSize);
    if(mMemoryCache == null){
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                // The cache size will be measured in kilobytes rather than
                // number of items.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
                    return bitmap.getByteCount() ;
                } else {
                    return bitmap.getRowBytes() * bitmap.getHeight();
                }
            }

        };
    }


}

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        Log.i("LruCacheManager","Bitmap is getting added, " + key);
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}

当我在AsyncTask中调用addBitmapToMemoryCache()以将位图保存到MemoryCache时。

但是当我致电getBitmapFromMemoryCache() null

//get cached Bitmap
    LruCacheManager imCache = new LruCacheManager();
    String imageKey = categoryNames[position];
    Bitmap cachedBm = imCache.getBitmapFromMemCache(imageKey);

    //Decide whatever use cached image or not
    if (cachedBm != null) {
        Log.i("AdapterGridView","Using cached image, " + imageKey);
        viewHolder.icon.setImageBitmap(cachedBm);
    } else {
        //starts Asynctask to scale pictures and show them, happens off the main thread
        new AsyncTaskImageLoader(viewHolder.icon, imageKey, mContext, imCache, mThumbIds[position]).execute();
    }

这意味着,一次又一次地调用AsyncTask。在AsyncTask中我将Bitmaps添加到LruCache。因为返回的Bitmap为null,所以LruCache中没有保存Bitmap。但我不知道为什么。 我也在线搜索,它可能与回收/垃圾收集器有关。

那我怎样才能正确加载缓存的图像呢?

任何帮助或澄清都是适当的。

修改

我在getView()方法中在BaseAdapter中调用它。我认为它与它有关。第一次,每个图像都被添加到缓存中,但是,第一个图像被添加了10次。

1 个答案:

答案 0 :(得分:1)

首先,我会设置一个任意的内存大小并尝试使用1张图像。其余的看起来很好......如果我下面的内容不起作用,请给我们打印出你的记忆等等。你可能没有。

在我的版本中,我通过

获得记忆
  final int maxMemory = (int) (Runtime.getRuntime().maxMemory());

然后将其设置为一小部分(我想我选了第8个) 当我返回得到大小时,我做/ 1024,我做设置内存。所以,如果你有1/1000的记忆,那么这就是可能的问题。

相关问题