ahmad
5/6/2016 - 3:47 PM

A helper class to Google volley. Made with inspiration from AFNetworking. Usage: volley = new VolleyHelper(this, "<BASEURL>"/*Ma

A helper class to Google volley. Made with inspiration from AFNetworking. Usage:

    volley = new VolleyHelper(this,
            "<BASEURL>"/*Maybe get url from getString*/);

    
    volley.post("<service_name>", null,
            new Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {

                    Log.i("Got JSON", response.toString());
                    
                }
            }, new ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley Error", "Error getting JSON", error);

                }
            });

import org.json.JSONObject;

import android.content.Context;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

public class VolleyHelper {

  private final Context mContext;
	private final RequestQueue mRequestQueue;
	private final ImageLoader mImageLoader;
	private final String mBaseUrl;
	
	public VolleyHelper(Context c, String baseUrl){
		mContext = c;
		mRequestQueue = Volley.newRequestQueue(mContext);
		mBaseUrl = baseUrl;
		mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache());
	}
	
	private String contructUrl(String method){
		return mBaseUrl + "/" + method;
	}
	
	public ImageLoader getImageLoader(){
		return mImageLoader;
	}
	
	public void get(String method, JSONObject jsonRequest,
            Listener<JSONObject> listener, ErrorListener errorListener){
		
		JsonObjectRequest objRequest = new JsonObjectRequest(Method.GET, contructUrl(method), jsonRequest, listener, errorListener);
		mRequestQueue.add(objRequest);
	}
	
	public void put(String method, JSONObject jsonRequest,
            Listener<JSONObject> listener, ErrorListener errorListener){
		
		JsonObjectRequest objRequest = new JsonObjectRequest(Method.PUT, contructUrl(method), jsonRequest, listener, errorListener);
		mRequestQueue.add(objRequest);
	}
	
	public void post(String method, JSONObject jsonRequest,
            Listener<JSONObject> listener, ErrorListener errorListener){
		
		JsonObjectRequest objRequest = new JsonObjectRequest(Method.POST, contructUrl(method), jsonRequest, listener, errorListener);
		mRequestQueue.add(objRequest);
	}
	
	public void delete(String method, JSONObject jsonRequest,
            Listener<JSONObject> listener, ErrorListener errorListener){
		
		JsonObjectRequest objRequest = new JsonObjectRequest(Method.DELETE, contructUrl(method), jsonRequest, listener, errorListener);
		mRequestQueue.add(objRequest);
	}
	
}