android : SoftReference / WeakReference example

Jomia picture Jomia · Jun 30, 2011 · Viewed 7.9k times · Source

I am getting OutOfMemoryError on my application. When i went through some tutorials, i came to know that, I can solve this issue by using Softreference/Weakreference. But I don't know that how to use Softreference/Weakreference.

Please suggest me some tutorials that providing examples for the Softreference or Weakreference.

Thank you...

Answer

Nayanesh Gupte picture Nayanesh Gupte · Mar 16, 2012
package com.myapp;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.WeakHashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;


public class BitmapSoftRefrences {


      public static String SDPATH = Environment.getExternalStorageDirectory()
        + "/MYAPP";

// 1. create a cache map
public static WeakHashMap<String, SoftReference<Bitmap>> mCache = new WeakHashMap<String, SoftReference<Bitmap>>();
public static String TAG = "BitmapSoftRefrences";

// 2. ask for bitmap
public static Bitmap get(String key) {
    if (key == null) {
        return null;
    }

    try {
        if (mCache.containsKey(key)) {

            SoftReference<Bitmap> reference = mCache.get(key);
            Bitmap bitmap = reference.get();
            if (bitmap != null) {
                return bitmap;
            }
            return decodeFile(key);
        }

    } catch (Exception e) {
        // TODO: handle exception
        Logger.debug(BitmapSoftRefrences.class,
                "EXCEPTION: " + e.getMessage());

    }

    // the key does not exists so it could be that the
    // file is not downloaded or decoded yet...

    File file = new File(SDPATH + "/" + key);

    if (file.exists()) {
        return decodeFile(key);
    } else {
        Logger.debug(BitmapSoftRefrences.class, "RuntimeException");

        throw new RuntimeException("RuntimeException!");
    }
}

// 3. the decode file will return bitmap if bitmap is not cached
public static Bitmap decodeFile(String key) {
    // --- prevent scaling
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inScaled = false;

    Bitmap bitmap = BitmapFactory.decodeFile(SDPATH + "/" + key, opt);

    mCache.put(key, new SoftReference<Bitmap>(bitmap));

    return bitmap;
}

public static void clear() {
    mCache.clear();
}

}