android: LruCache 返回空

标签 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;
        }
    };
}

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

最佳答案

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

关于android: LruCache 返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21796665/

相关文章:

android - 如何在手机开机时自动运行应用程序

Android Studio 不启动 : Could not find or load main class com. intellij.idea.Main

android - 找不到 firebase-messaging.jar - Android 构建错误

PHP算法大数组内存问题

java - 可用于单元测试的 Netty 4/5 确定性缓冲区泄漏检测

c# System.OutOfMemoryException 我该如何解决?

android - 服务器需要连接设置更新android studio

javascript - 具有 ID 属性的动态 DOM 对象的 IE9 内存泄漏

java - 运行多线程代码时内存不足异常

android - 在 Android 中显示来自服务器字节数组的图像