LruCache not working - android

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");
Hello, here is a code. I get bitmap from URL successfully (Log says Bitmap is not null and I can display it easy). Then I am trying to put it into LruCache and get it back, but it return null. (Log says newBitmap is null). Where is my mistake? Please, tell me.
Android 4.1.2 Cache size 8192 Kb.

If it is 1.19 MB on disk but ~ 9 MB in memory, that means that as a compressed JPEG file, it's 1.19 MB and once you extract that into a Bitmap (uncompressed) that can be displayed, it will take up 9 MB in memory. If it's a 1920 x 1200 pixel image as suggested by the url in your code snippet, the image will take up 1920 x 1200 x 4 bytes of memory (4 bytes for each pixel to represent ARGB values from 0 to 256 times 2.3 million total pixels = 9,216,000 bytes). If you're using 1/8 of your available memory for this cache, it's possible/likely that 9MB exceeds that total memory space so the Bitmap never makes it into the cache or is evicted immediately.
You're probably going to want to downsample the image at decoding time if it's that large (using BitmapFactory.Options.inSampleSize...lot's of documentation on the web for using that if you're not already familiar).
Also, you're using Runtime.maxMemory to compute your cache size. This means you're requesting the maximum amount of memory that the whole VM is allowed to use.
http://developer.android.com/reference/java/lang/Runtime.html#maxMemory%28%29
The more common approach is the use the value given back to you by the ActivityManager.getMemoryClass() method.
Here's an example code snippet and the method definition in the docs for reference.
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
int memClassBytes = am.getMemoryClass() * 1024 * 1024;
int cacheSize = memClassBytes / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize)
http://developer.android.com/reference/android/app/ActivityManager.html#getMemoryClass%28%29

You can also recycle bitmaps that pops out from lrucache
final Bitmap bmp = mLruCache.put(key, data);
if (bmp != null)
bmp.recycle();

The Android example was wrong when dividing Runtime maxMemory by 1024 in the following line:
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
The unit of the maxMemory is Byte which is the same with the 'cacheSize' ('/ 8' just means it will use eighth of the available memory of the current Activity). Therefore, '/ 1024' will make the 'cacheSize' extremely small such that no bitmap can be actually 'cached' in 'mMemoryCache'.
The solution will be delete '/ 1024' in the above code.

Related

Android LruCache cache size parameter

I am trying to follow a 2 year old tutorial on android regarding the usage of LruCache and some samples I have googled so far have the same method which is to pass an value(int) that is converted to KiB.
final int maxMemory = (int)(Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8; //use 1/8th of what is available
imageCache = new LruCache<>(cacheSize);
However as taken from Google's documentation, the passed int value seems to be converted to bytes (from MiB):
https://developer.android.com/reference/android/util/LruCache.html
int cacheSize = 4 * 1024 * 1024; // 4MiB
LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
}
I would like to know which one is the correct unit of measurement.
Any answers would be greatly appreciated..
An LruCache uses the method sizeOf to determine the current size of the cache, and whether or not the cache is full. (i.e., sizeOfis called on each item in the cache and added up to determine the total size). Thus, the correct value for the constructor depends on the implementation of sizeOf.
By default, sizeOf always returns 1, meaning that the int maxSize specified in the constructor is simply the number of items the cache can hold.
In the example, sizeOf has been overridden to return the number of bytes in each bitmap. Thus, the int maxSize in the constructor is the maximum number of bytes the cache should hold.
What you are following comes from https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
As you can see, the rationale is that LruCache needs an int. Because memory can be to big to address bytes with ints, it considers kilo bytes instead. So:
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
But also, in the same training,
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
The size of the bitmap is also expressed in kilo bytes.
In the class documentation, the author uses bytes because 4.2^20 fits in an int.

why do we divide by 1024 for a custom LRUCache in android

final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
AND
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024 / 8);
Howcome i have to divide the maxMemory by 1024. Furthermore, why would one divide again by 8. I've seen it done both ways in the tutorials i've seen for writing a custom LRUCache yet i don't understand the implications?
Howcome i have to divide the maxMemory by 1024
You do not have to divide anything by anything to use LRUCache.
What you do need is for the maxSize that you pass into the LRUCache constructor to be in the same units as you use in your sizeOf() method.
For example, here is a sample bit of LRUCache code, taken from the JavaDocs:
int cacheSize = 4 * 1024 * 1024; // 4MiB
LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
}
Here, the unit of size is a byte. So, the comment indicates that they are passing in a number of bytes representing 4MiB, and sizeOf() returns the size of the Bitmap in bytes.

Optimal BitmapLRU Cache Size Android 1/8th of total memory or three screens of memory?

What is the optimal BitmapLRU image cache size on Android for caching images? I am targeting sdk 2.3.5+ basically 10+ devices. Currently I am taking the larger amount of these two calculations as shown below. Is 1/8th a safe pct to avoid out of memory errors?
Here is how I am calculating it now:
private static int calculateImageCacheSize(Context ctx)
{
// Gets the dimensions of the device's screen
DisplayMetrics dm = ctx.getResources().getDisplayMetrics();
int screenWidth = dm.widthPixels;
int screenHeight = dm.heightPixels;
// Assuming an ARGB_8888 pixel format, 4 bytes per pixel
int size = screenWidth * screenHeight * 4;
// 3 bitmaps to store therefore multiply bitmap size by 3
int cacheSize = size * 3;
int cachePercentOfMemory = getPercentageOfTotalMemory(8);
int retCacheSize = cacheSize;
if (retCacheSize < cachePercentOfMemory)
retCacheSize = cachePercentOfMemory;
return retCacheSize;
}
public static int getPercentageOfTotalMemory(int divider)
{
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / divider;
return cacheSize;
}
There's no one "right" answer, and really depends what your app is doing. If it does lots network connections, have complex data structures, decodes lots of Bitmaps...etc, then the code itself would consume quite a bit of memory and setting image cache size to 1/8 should be reasonable. However if your app is quite simplistic you can probably raise the amount of memory allocated for caching.
So if you are really concerned about it, the only way to know is to have tests testing your app and see which configuration works the best for this particular app.

Android: bitmap.getByteCount() in API lesser than 12

When i searched for how to find the size of an image before saving it on the SD card, i found this:
bitmap.getByteCount();
but that method is added in API 12 and i am using API 10. So again i found out this:
getByteCount() is just a convenience method which does exactly what you have placed in the else-block. In other words, if you simply rewrite getSizeInBytes to always return "bitmap.getRowBytes() * bitmap.getHeight()"
here:
Where the heck is Bitmap getByteCount()?
so, by calculating this bitmap.getRowBytes() * bitmap.getHeight() i got the value 120000 (117 KB).
where as the image size on the SD card is 1.6 KB.
What am i missing? or doing wrong?
Thank You
You are doing it correctly!
A quick way to know for sure if the values are valid, is to log it like this:
int numBytesByRow = bitmap.getRowBytes() * bitmap.getHeight();
int numBytesByCount = bitmap.getByteCount();
Log.v( TAG, "numBytesByRow=" + numBytesByRow );
Log.v( TAG, "numBytesByCount=" + numBytesByCount );
This gives the result:
03-29 17:31:10.493: V/ImageCache(19704): numBytesByRow=270000
03-29 17:31:10.493: V/ImageCache(19704): numBytesByCount=270000
So both are calculating the same number, which I suspect is the in-memory size of the bitmap. This is different than a JPG or PNG on disk as it is completely uncompressed.
For more info, we can look to AOSP and the source in the example project. This is the file used in the example project BitmapFun in the Android developer docs Caching Bitmaps
AOSP ImageCache.java
/**
* Get the size in bytes of a bitmap in a BitmapDrawable.
* #param value
* #return size in bytes
*/
#TargetApi(12)
public static int getBitmapSize(BitmapDrawable value) {
Bitmap bitmap = value.getBitmap();
if (APIUtil.hasHoneycombMR1()) {
return bitmap.getByteCount();
}
// Pre HC-MR1
return bitmap.getRowBytes() * bitmap.getHeight();
}
As you can see this is the same technique they use
bitmap.getRowBytes() * bitmap.getHeight();
References:
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
http://code.google.com/p/adamkoch/source/browse/bitmapfun/
For now i am using this:
ByteArrayOutputStream bao = new ByteArrayOutputStream();
my_bitmap.compress(Bitmap.CompressFormat.PNG, 100, bao);
byte[] ba = bao.toByteArray();
int size = ba.length;
to get total no.of bytes as size. Because the value i get here perfectly matches the size(in bytes) on the image on SD card.
Nothing is missing! Your codesnippet shows exact the implementation from Android-Source:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.1.1_r1/android/graphics/Bitmap.java#Bitmap.getByteCount%28%29
I think the differences in size are the result of image-compressing (jpg and so on).
Here is an alternative way:
public static int getBitmapByteCount(Bitmap bitmap) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1)
return bitmap.getRowBytes() * bitmap.getHeight();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
return bitmap.getByteCount();
return bitmap.getAllocationByteCount();
}
A statement from the IDE for getAllocationByteCount():
This can be larger than the result of getByteCount() if a bitmap is
reused to decode other bitmaps of smaller size, or by manual
reconfiguration. See reconfigure(int, int, Bitmap.Config),
setWidth(int), setHeight(int), setConfig(Bitmap.Config), and
BitmapFactory.Options.inBitmap. If a bitmap is not modified in this
way, this value will be the same as that returned by getByteCount().
may u can try this code
int pixels = bitmap.getHeight() * bitmap.getWidth();
int bytesPerPixel = 0;
switch(bitmap.getConfig()) {
case ARGB_8888:
bytesPerPixel = 4;
break;
case RGB_565:
bytesPerPixel = 2;
break;
case ARGB_4444:
bytesPerPixel = 2;
break;
case ALPHA_8 :
bytesPerPixel = 1;
break;
}
int byteCount = pixels / bytesPerPixel;
the image on the sd card has a different size because it's compressed. on the device it will depend on the width/height
Why don't you try dividing it between 1024? To get the KB instead of Bytes.

Android: Image cache strategy and memory cache size

I'm implementing an image cache system for caching downloaded image.
My strategy is based upon two-level cache:
Memory-level and disk-level.
My class is very similar to the class used in the droidfu project
My downloaded images are put into an hashmap and the Bitmap objet is
wrapped inside a SoftRererence object. Also every image is saved
permanently to the disk.
If a requested image is not found into the
Hashmap<String,SoftReference<Bitmap>> it will be searched on the disk,
readed, and then pushed back into the hashmap. Otherwise the image will be
downloaded from the network.
Since I store the images into the phisical device momery, I have added a check for preserve the device space and stay under a 1M of occupied space:
private void checkCacheUsage() {
long size = 0;
final File[] fileList = new File(mCacheDirPath).listFiles();
Arrays.sort(fileList, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.valueOf(f2.lastModified()).compareTo(
f1.lastModified());
}
});
for (File file : fileList) {
size += file.length();
if (size > MAX_DISK_CACHE_SIZE) {
file.delete();
Log.d(ImageCache.class.getSimpleName(),
"checkCacheUsage: Size exceeded " + size + "("
+ MAX_DISK_CACHE_SIZE + ") wiping older file {"+file.toString()+"}");
}
}
}
This method is called sometime afte a disk writing:
Random r = new Random();
int ra = r.nextInt(10);
if (ra % 2 == 0){
checkCacheUsage();
}
What I'd like to add is the same check on the HashMap size to prevent it will grow too much. Something like this:
private synchronized void checkMemoryCacheUsage(){
long size = 0;
for (SoftReference<Bitmap> a : cache.values()) {
final Bitmap b = a.get();
if (b != null && ! b.isRecycled()){
size += b.getRowBytes() * b.getHeight();
}
if (size > MAX_MEMORY_SIZE){
//Remove some elements from the cache
}
}
Log.d(ImageCache.class.getSimpleName(),
"checkMemoryCacheUsage: " + size + " in memory");
}
My question is:
What could be a right MAX_MEMORY_SIZE value?
Also, Is it a good approach?
A good answer also could be: "Don't do it! SoftReference is already enough"
Don't do it! SoftReference is already enough!
Actually SoftReference is designed to do exactly what you need.
Sometimes SoftReference doesn't do what you need. Then you just get rid of SoftReference and write your own memory management logic. But as far as you use SoftReference you should not be worried about memory consumption, SoftReference does it for you.
I am using one-third of the heap for Image cache.
int memoryInMB = activityManager.getMemoryClass();
long totalAppHeap = memoryInMB * 1024 * 1024;
int runtimeCacheLimit = (int)totalAppHeap/3;
By the way, about soft reference, in Android Soft references do not work as you expect. There is a platform issue that soft references are collected too early, even when there is plenty of memory free.
Check http://code-gotcha.blogspot.com/2011/09/softreference.html
I've been looking into different caching mechanisms for my scaled bitmaps, both memory and disk cache examples. The examples where to complex for my needs, so I ended up making my own bitmap memory cache using LruCache.
You can look at a working code-example here or use this code:
Memory Cache:
public class Cache {
private static LruCache<Integer, Bitmap> bitmaps = new BitmapLruCache();
public static Bitmap get(int drawableId){
Bitmap bitmap = bitmaps.get(drawableId);
if(bitmap != null){
return bitmap;
} else {
bitmap = SpriteUtil.createScaledBitmap(drawableId);
bitmaps.put(drawableId, bitmap);
return bitmap;
}
}
}
BitmapLruCache:
public class BitmapLruCache extends LruCache<Integer, Bitmap> {
private final static int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
private final static int cacheSize = maxMemory / 2;
public BitmapLruCache() {
super(cacheSize);
}
#Override
protected int sizeOf(Integer key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than number of items.
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}
}

Categories

Resources