What is Android?
Android, the widely popular operating system, is the beating heart behind millions of smartphones and tablets globally. Developed by Google, Android is an open-source platform that powers a diverse range of devices, offering users an intuitive and customizable experience. With its user-friendly interface, Android provides easy access to a plethora of applications through the Google Play Store, catering to every need imaginable. From social media and gaming to productivity and entertainment, Android seamlessly integrates into our daily lives, ensuring that the world is at our fingertips. Whether you're a tech enthusiast or a casual user, Android's versatility and accessibility make it a cornerstone of modern mobile technology.
Clearing an LruCache in Android
In Android development, LruCache (Least Recently Used Cache) is a handy utility for caching frequently used data like images, objects, and other resources that you want to store in memory for fast access. However, there are scenarios where you might want to clear the cache — for example, to free up memory when your app no longer needs cached data, or when the user logs out and you need to clear sensitive data.
Luckily, LruCache provides a straightforward method to clear the cache, and in this article, we’ll walk you through how to clear an LruCache and discuss best practices for cache management.
1. Using the evictAll() Method
The easiest way to clear all items in an LruCache is by using the evictAll() method, which removes all cached data at once.
Example: Clearing the Entire LruCache
Here’s an example where we initialize an LruCache, add data to it, and then clear it using the evictAll() method:
import android.graphics.Bitmap;
import android.util.LruCache;
public class ImageCache {
private LruCache<String, Bitmap> mMemoryCache;
public ImageCache() {
// Set the cache size to 4MB
final int cacheSize = 4 * 1024 * 1024; // 4MB
mMemoryCache = new LruCache<>(cacheSize);
}
// Method to add a bitmap to the cache
public void addBitmapToCache(String key, Bitmap bitmap) {
if (getBitmapFromCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
// Method to get a bitmap from the cache
public Bitmap getBitmapFromCache(String key) {
return mMemoryCache.get(key);
}
// Method to clear all items from the cache
public void clearCache() {
mMemoryCache.evictAll(); // This clears the cache
}
}
Explanation:
-
evictAll(): This method removes all entries from the cache, effectively clearing it. You can call this method when you want to clear the entire cache, for example, when the user logs out or when you want to free up memory.
-
addBitmapToCache(): Adds a
Bitmapto the cache if it’s not already present. -
getBitmapFromCache(): Retrieves the cached
Bitmapbased on the provided key.
2. Removing Specific Items from the Cache
If you don’t want to clear the entire cache, but rather remove specific items, you can use the remove() method. This method allows you to remove a specific entry from the cache by its key.
Example: Removing a Specific Item from the Cache
public void removeItemFromCache(String key) {
mMemoryCache.remove(key); // Removes the specified item from the cache
}
This method will remove the cache entry corresponding to the provided key without affecting the rest of the cached data.
3. Clearing the Cache on Low Memory
In some cases, you may want to clear the cache when the device is running low on memory. Android provides a low-memory warning that can be handled via the onTrimMemory() method, which can help you clear the cache when the system needs memory.
Example: Handling Low Memory and Clearing Cache
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
// If the system is running low on memory, clear the cache
if (level >= TRIM_MEMORY_RUNNING_CRITICAL) {
mMemoryCache.evictAll(); // Clear all cache entries
}
}
In this example:
- The
onTrimMemory()method is overridden to listen for low memory conditions. - If the system is running critically low on memory (using
TRIM_MEMORY_RUNNING_CRITICAL), the cache is cleared using theevictAll()method to free up memory.
4. Best Practices for Clearing an LruCache
Here are some best practices to consider when working with LruCache:
-
Only clear when necessary: You don't need to clear the cache frequently. Typically, LruCache will automatically handle memory evictions when the cache size exceeds the limit. Clearing the cache should be done only when necessary, such as during user logout, app exit, or when switching to a different user profile.
-
Use
evictAll()cautiously: CallingevictAll()clears everything in the cache. If your app relies heavily on cached data, this may result in a noticeable performance hit when data needs to be reloaded. Only clear the cache when the data is no longer needed or when freeing up memory is a priority. -
Clear cache on low memory: For large apps that store a lot of data in the cache, consider listening to low memory events and clearing the cache in such scenarios. This ensures that your app won’t consume unnecessary memory when the system is under memory pressure.
5. Clearing the Cache in a RecyclerView Adapter
In some cases, you may want to clear or remove cache items in a more complex scenario, such as when displaying images in a RecyclerView.
Example: Clearing Cache in RecyclerView Adapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
private List<String> imageUrls;
private ImageCache imageCache;
public ImageAdapter(List<String> imageUrls, ImageCache imageCache) {
this.imageUrls = imageUrls;
this.imageCache = imageCache;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String imageUrl = imageUrls.get(position);
// Check if the image is already in cache
Bitmap cachedBitmap = imageCache.getBitmapFromCache(imageUrl);
if (cachedBitmap != null) {
holder.imageView.setImageBitmap(cachedBitmap);
} else {
// Load the image (you can use libraries like Glide or Picasso here)
Bitmap bitmap = loadImage(imageUrl);
imageCache.addBitmapToCache(imageUrl, bitmap);
holder.imageView.setImageBitmap(bitmap);
}
}
@Override
public int getItemCount() {
return imageUrls.size();
}
// Method to clear cache when needed (for example, when the user logs out)
public void clearCache() {
imageCache.clearCache(); // Clears the cache in the adapter
}
public static class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
}
}
In this example:
- clearCache(): You can call this method when clearing the cache is necessary, for example, when logging out or when switching between different sets of images.
Conclusion
Clearing an LruCache in Android is a straightforward process, and it is useful for managing memory efficiently, particularly when your app deals with a lot of data that can be cached. Here are the key ways to clear the cache:
- evictAll(): Clears all entries in the cache.
- remove(): Removes a specific entry from the cache.
- Low memory handling: Listen to low memory events and clear the cache when necessary.
- Clear cache based on use case: Consider when clearing the cache is needed to optimize memory usage, such as on user logout or when switching between different sets of data.
By using LruCache effectively and managing its contents appropriately, you can improve both the performance and memory usage of your Android app, leading to a better user experience.

0 Comments