Create memory cache for android
July 30, 2015 5:34 am
This android video tutorial explains how to create memory cache for android. Using this method will have a dramatic effect on performance for android applications.
Implementation
Create LruCache
final int maxMemorySize = (int) Runtime.getRuntime().maxMemory() / 1024; final int cacheSize = maxMemorySize / 10; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount() / 1024; } };
Create cache getters & setters
public static Bitmap getBitmapFromMemoryCache(String key) { return mMemoryCache.get(key); } public static void setBitmapToMemoryCache(String key, Bitmap bitmap) { if(getBitmapFromMemoryCache(key) == null) { mMemoryCache.put(key, bitmap); } }
Add bitmap to cache in AsyncTask doInBackground method
@Override protected Bitmap doInBackground(File... params) { // return BitmapFactory.decodeFile(params[0].getAbsolutePath()); mImageFile = params[0]; // return decodeBitmapFromFile(params[0]); Bitmap bitmap = decodeBitmapFromFile(mImageFile); CamaraIntentActivity.setBitmapToMemoryCache(mImageFile.getName(), bitmap); return bitmap; }
Check for Bitmap in cache in RecyclerView adapter
@Override public void onBindViewHolder(ViewHolder holder, int position) { File imageFile = imagesFile.listFiles()[position]; Bitmap bitmap = CamaraIntentActivity.getBitmapFromMemoryCache(imageFile.getName()); if(bitmap != null) { holder.getImageView().setImageBitmap(bitmap); } else if(checkBitmapWorkerTask(imageFile, holder.getImageView())) { BitmapWorkerTask bitmapWorkerTask = new BitmapWorkerTask(holder.getImageView()); AsyncDrawable asyncDrawable = new AsyncDrawable(holder.getImageView().getResources(), placeHolderBitmap, bitmapWorkerTask); holder.getImageView().setImageDrawable(asyncDrawable); bitmapWorkerTask.execute(imageFile); } }
Conclusion
Implementing memory cache will normally be simple & straight forward, which will result in significant & visible performance improvements. But care does need to be taken in deciding the size of the cache, if too large out of memory errors will result.
Category: Performance, tutorials