Skip to content

Instantly share code, notes, and snippets.

@muratcanbur
Created April 20, 2015 08:32
Show Gist options
  • Save muratcanbur/53e35e2a9ba01340bedc to your computer and use it in GitHub Desktop.
Save muratcanbur/53e35e2a9ba01340bedc to your computer and use it in GitHub Desktop.
This is a Singleton Pattern class that provides RequestQueue
public class VolleySingleton {
public static final String TAG = VolleySingleton.class
.getSimpleName();
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private VolleySingleton(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 VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(tag);
getRequestQueue().add(req);
}
/**
* if you want to cancel your request, then use this method!
*/
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment