using volley multiple times with different params (object oriented)

755 views Asked by At

In my application i use volley very much times, and every time i need to create class because different params.

Is there a way to reuse volley multiple times with different params ?

 private void sendReservation(String url) {


    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response);


                    } catch (JSONException e) {
                        e.printStackTrace();

                    }


                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Creating parameters
            Map<String, String> params = new Hashtable<String, String>();
            //Adding parameters
            User user = prefManager.getUser();
            params.put("id", Id);

            return postParams.checkParams(params);
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    int x = 0;// retry count
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 48,
            x, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    requestQueue.add(stringRequest);
}

Above class i use it with similar request that have the same params.

What i need is to reuse the same method sendReservation() with more than 1 params or what ever params i pass.

Assume i have one thread post 2 params like :

 params.put("id", Id);
params.put("name", name);

and another post three params like :

    params.put("id", Id);
    params.put("name", name);
params.put("type", type);

How to handle that ?

feel free to ask any question.

1

There are 1 answers

0
Vishal Chhodwani On

This is already reduced code provided by Volley, at-least you have to set params when you are calling any service.

But Still you can create a controller class where you will send a serviceCode(any unique number created by) and according to serviceCode create your params in controller class and call service.

In this case you have to write only 2 lines of code.

Eg.

ServiceController controller = new ServiceController(context);
controller.call(SERVICE_CODE, responseListner);

The above is just an example code to call your controller class.

Edit

Here is the complete code that will help you.

Create ServiceController class

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.cdnsol.interfaces.ConstantsLib;
import com.cdnsol.interfaces.UrlConstants;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by vishalchhodwani on 28/8/17.
 */
public class ServiceController {

    Context context;

    public ServiceController(Context context)
    {
        this.context = context;
    }

    public void call(int serviceCode, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener)
    {
        if (serviceCode == ConstantsLib.LOGIN_REQUEST)
        {
            HashMap<String, String> stringParams = new HashMap<>();
            stringParams.put("password", "123456");
            stringParams.put("email", "[email protected]");

            createRequest(stringParams, listener, errorListener);
        }
        if (serviceCode == ConstantsLib.SIGN_UP_REQUEST)
        {
            HashMap<String, String> stringParams = new HashMap<>();
            stringParams.put("password", "123456");
            stringParams.put("email", "[email protected]");
            stringParams.put("name", "abc");

            createRequest(stringParams, listener, errorListener);
        }
    }

    private void createRequest(HashMap<String, String> params, Response.Listener<JSONObject> responseListener, Response.ErrorListener errorListener)
    {
        try
        {
            NetworkRequest networkRequest = new NetworkRequest(context, UrlConstants.LOGIN_URL, params,
                    true, responseListener, errorListener);

            RequestQueue requestQueue = Volley.newRequestQueue(context);
            int x = 0;// retry count
            networkRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 48,
                    x, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requestQueue.add(networkRequest);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

Now call your service from activity or fragment

ServiceController controller = new ServiceController(LoginActivity.this);
controller.call(ConstantsLib.LOGIN_REQUEST, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {

        // Handle Response
        }
        },

        new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

        // Handle Error
        }
        });