GridView のビットマップを 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()
Bitmaps を MemoryCache に保存するために AsyncTaskを呼び出したとき。
しかし、私が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 im で、ビットマップを LruCache に追加します。返された Bitmap は null であるため、LruCache に保存されている Bitmap はありません。しかし、私には理由がわかりません。私もオンラインで検索しましたが、リサイクル/ガベージコレクターと何か関係があるかもしれません。
では、キャッシュされた画像を適切にロードするにはどうすればよいでしょうか?
ヘルプや説明は適切です。
編集:
これを getView() メソッドの BaseAdapter 内で呼び出します。それと関係があると思います。最初はそれぞれの画像が Cache に追加されますが、その後、最初の画像が 10 回ほど追加されます。