2014-09-03 59 views
0

我在GridView中將位圖緩存到LruCache。我給這個經理,見下圖:位圖正在保存到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); 
} 

當我打電話addBitmapToMemoryCache()在我的AsyncTask位圖保存到的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。由於返回的位圖爲空,因此LruCache中沒有保存位圖。但我不知道爲什麼。 我也在網上搜索,它也許可以做一些與回收/垃圾收集器。

那麼我怎樣才能正確地加載緩存圖片?

任何幫助或澄清並欣賞。

編輯:

我在getView調用這個內部BaseAdapter()方法。我認爲這與它有關。這是第一次,每個圖像被添加到緩存,但是,第一個圖像被添加了10次。

回答

1

首先,我將設置一個任意的內存大小,並嘗試與1圖像。其餘的看起來不錯......如果我下面有什麼不起作用,請給我們打印出你的記憶,等等。你可能沒有。

在我的版本我得到

final int maxMemory = (int) (Runtime.getRuntime().maxMemory()); 

內存中,然後由一小部分設置(我想我拿起一個8) 我做的/ 1024,當我回到獲得的大小,我做它設置內存。所以,如果你有,你認爲你有記憶的1/1000,這將是可能的問題..

+0

爲@ StarWind0說,最初的高速緩存大小是非常低的。在我的設備上達到了16k。你的位圖可能會被自動丟棄 – 2018-02-27 16:12:57

+0

是的,3年後我永遠不會使用最大內存的一小部分。我會下載圖片樣本,然後決定最少需要多少。 – StarWind0 2018-02-27 20:13:29

相關問題