android:LruCache返回null

时间:2014-02-15 11:07:58

标签: android memory-leaks out-of-memory bitmapimage android-lru-cache

我是Android中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;
        }
    };
}

我不知道为什么不工作:( 感谢

3 个答案:

答案 0 :(得分:1)

这是因为要存储的数据的缓存大小较低,所以通过给出来检查它 final int cacheSize = maxMemory;或者通过足够的缓存大小

答案 1 :(得分:0)

这对我有用:

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

答案 2 :(得分:0)

你的问题就在这里

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

应该是

return (bitmap.getRowBytes() * bitmap.getHeight())/1024;
相关问题