Besides using Bitmap.recycle() as suggested (which is not suitable for all situations and it's a pain in the neck to be asking: "do I still need this bitmap?"), I always use this technique which works really fine:
// 1. create a cache map private WeakHashMap<String, SoftReference<Bitmap>> mCache;
As you can see, it's a hash map of WeakReferences with a SoftReference as the values.
//2. when you need a bitmap, ask for it: public Bitmap get(String key){ if( key == null ){ return null; } if( mCache.containsKey(key) ){ SoftReference<Bitmap> reference = mCache.get(key); Bitmap bitmap = reference.get(); if( bitmap != null ){ return bitmap; } return decodeFile(key); } // the key does not exists so it could be that the // file is not downloaded or decoded yet... File file = new File(Environment.getExternalStorageDirectory(), key); if( file.exists() ){ return decodeFile(key); } else{ throw new RuntimeException("Boooom!"); } }
This will check the cache map. If the file was already decoded, it will be returned; otherwise it will be decoded and cached.
//3. the decode file will look like this in your case private Bitmap decodeFile(String key) { Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"//Pics/"+key); mCache.put(key, new SoftReference<Bitmap>(bitmap)); return bitmap; }
Working with soft references is nice because you shift the responsibility of removing bitmaps from memory to the OS.