final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
final int cacheSize = maxMemory/8;
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.
return bitmap.getByteCount()/1024;
}
};
URL url = new URL("http://s2.goodfon.ru/image/260463-1920x1200.jpg");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) url.getContent(), null, options);
if(bitmap != null)
Log.i("Success", "BITMAP IS NOT NULL");
String key = "myKey";
Log.i("Get is null", "putting myKey");
mMemoryCache.put(key, bitmap);
Bitmap newBitmap = mMemoryCache.get(key);
if(newBitmap == null)
Log.i("newBitmap", "is null");
你好,這裏是一個代碼。我成功地從URL獲取位圖(日誌說,位圖不是空的,我可以很容易地顯示它)。然後我試圖將它放入LruCache中並將其取回,但它返回null。 (日誌說newBitmap爲空)。我的錯誤在哪裏?請告訴我。 Android 4.1.2緩存大小8192 Kb。LruCache不工作
那麼,你有沒有試過,你的緩存大小的計算是正確的?那麼'sizeOf()'輸出的是什麼?你確定圖片真的在緩存裏嗎? – ConcurrentHashMap 2013-03-17 10:46:41
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html。 – Raghunandan 2013-03-17 10:56:56
哦,那個圖像是9000 kb,我認爲它的文件是1.19 MB。問題解決了。謝謝。 Plaese告訴我,爲什麼1.19 MB文件在getByteCount/1024中返回9000 kb? – Faceles 2013-03-17 11:06:46