android:LruCache 返回空值



我是安卓 LruCache 的新手,我想在此缓存上放置并获取位图图像 (JPEG) 以防止内存错误和内存异常,所以我不明白为什么我的代码不起作用。这是我的代码:

ImageView imageview = (ImageView)findViewById(R.id.imageView1);
Bitmap b = BitmapFactory.decodeFile(imagePath); 
mMemoryCache.put("mykey", b);
b = mMemoryCache.get("mykey");
imageview.setImageBitmap(b);

这是我的 LruCache 代码:

import android.support.v4.util.LruCache;
...
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    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) {
            return (bitmap.getRowBytes() * bitmap.getHeight() * 4)/1024;
        }
    };
}

我不知道为什么不起作用:(谢谢

这是因为要存储的数据的缓存大小较低,所以..通过给予来检查它最终的整数缓存大小 = 最大内存;或有足够的缓存大小

这对

我有用:

final int memClass = ((ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
final int cacheSize =  1024 *  1024 *memClass ;

你的问题就在这里

return (bitmap.getRowBytes() * bitmap.getHeight() * 4)/1024;

它应该是

return (bitmap.getRowBytes() * bitmap.getHeight())/1024;

最新更新