The class LruCache to manage a cache of bitmap objects

The intensive use of many images in an app can create difficulties to the responsiveness and to memory, shown by warnings like ANR (Application Not Responding) or errors like OutOfMemoryError.

Consider an app that displays images in a list using ListView, GridView or RecyclerView, for better responsiveness of the app all the images should be loaded into an array in memory, but this could lead to an error because there is a limit to the memory that an app can use, often in the range 16MB – 48MB.
The alternative is to save the images to files or a database sqlite of the device and load into memory only those currently displayed to the user but the reading time by a physical memory can be perceived by the user, and this would make slow the app or could lead to an ANR, even the same image can be charged repeatedly scrolling the list up and down.
The class LruCache saves the images in a cache then these images can be loaded only once, it is a good compromise between responsiveness and memory usage.

LruCache is part of the Support Pack that can be imported using Gradle:

Create the class BitmapArray, a wrapper for a LruCache object that in this example uses generics as a Long and a Bitmap; Long id the key to access to Bitmap and you can replace it with other objects as Integer or String.

PERC is a value between 0 and 1 and sets the percentage of memory reserved to the cache, in this example it is 30%.
The get and put methods are the getter and setter to manage the images in the cache, every time they are called the image is placed at the head of the queue of the cache, in case you tried to insert an image with cache already full the images at the tail of the queue of the cache are released.

In the adapter class that manage the list of the images you’ll probably have to write code like this:

Caching Bitmaps
Manage Memory on Android 3.0 and Higher

Leave a Comment

Your email address will not be published.