0

I was reading the Google Developer's Guide on the Volley Framework and found that they used this line in the code:

 private static Context mCtx;

The entire code for a Volley Singleton (from https://developer.android.com):

public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
        private final LruCache<String, Bitmap>
                cache = new LruCache<String, Bitmap>(20);

        @Override
        public Bitmap getBitmap(String url) {
            return cache.get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            cache.put(url, bitmap);
        }
    });
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

public ImageLoader getImageLoader() {
    return mImageLoader;
}

I had learnt until now that using static Context fields are memory leaks. However, I can't understand why such a thing is used here.

I would like to know how/ why this is not a memory leak. (Assuming it is not, as it is up on the tutorial site)

Debanik Dawn
  • 797
  • 5
  • 28
  • "I had learnt until now that using static Context fields are memory leaks" Where have you learned that and what does it mean to you? – Oleg Sep 23 '17 at 12:32
  • Well for starters, android studio prompt - "Warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)." – Debanik Dawn Sep 23 '17 at 12:37
  • https://stackoverflow.com/a/40094872/1398418 – Oleg Sep 23 '17 at 12:40
  • Possible duplicate of ["Warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)"](https://stackoverflow.com/questions/40094020/warning-do-not-place-android-context-classes-in-static-fields-this-is-a-memor) – Oleg Sep 23 '17 at 12:42

0 Answers0