It was because of low cache Size for data to store so ..check it by giving final int cacheSize = maxMemory; or by sufficient cache size
android: LruCache return null
-
12-10-2022 - |
题
I am new to LruCache in android and i want to put and get bitmap images (JPEG) on this cache to prevent memory errors and memory exception, so i can't understand why my code does not work. here is my code:
ImageView imageview = (ImageView)findViewById(R.id.imageView1);
Bitmap b = BitmapFactory.decodeFile(imagePath);
mMemoryCache.put("mykey", b);
b = mMemoryCache.get("mykey");
imageview.setImageBitmap(b);
and this is my LruCache code:
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;
}
};
}
i don't know why is not working :( thanks
解决方案
其他提示
This works for me:
final int memClass = ((ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
final int cacheSize = 1024 * 1024 *memClass ;
your problem lies here
return (bitmap.getRowBytes() * bitmap.getHeight() * 4)/1024;
it should be
return (bitmap.getRowBytes() * bitmap.getHeight())/1024;
不隶属于 StackOverflow