Skip to content

Instantly share code, notes, and snippets.

@silmood
Last active March 9, 2018 17:16
Show Gist options
  • Select an option

  • Save silmood/cc55f31c06da8a442771 to your computer and use it in GitHub Desktop.

Select an option

Save silmood/cc55f31c06da8a442771 to your computer and use it in GitHub Desktop.
Volley Singleton
RequestQueue queue = VolleyClient.getInstance(getActivity()).getRequestQueue(); //Obtain the instance
StringRequest volleyRequest = new StringRequest(Request.Method.POST,url, //Change the url parameter
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonResponse = new JSONArray(response); // Convert string to JSONArray
//TODO: parse the JSON or whatever
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
//Post method parameters
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//TODO: Change params and values
params.put("paramName", "value");
params.put("paramName", "value");
return params;
}
};
//TODO: Change the retry policy
volleyRequest.setRetryPolicy(new DefaultRetryPolicy());
queue.add(volleyRequest);
public class VolleyClient extends Application{
public static final String TAG = VolleyClient.class
.getSimpleName();
private static VolleyClient mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
private VolleyClient(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized VolleyClient getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleyClient(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, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
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