Webservices Api Calling Using Volley In Common Class

Posted By : Keshav Gupta | 07-Sep-2017

Step1:Downlaod volley.jar lib and copy it in  app/libs/ and add in project

Step2: Create a interface class named as ApiResponseInterface  which will be having two methods declared one for success and one for failure.It will be like.

public interface ApiResponseInterface {
     void isError(VolleyError volleyError,int ServiceCode);
     void isSuccess(String response, int ServiceCode);
}

Step3: Create a class named as ApiRequestCode which contain requestcode for every call which will be used in interface callback on fragment and activity to identify which service call result is in success or failure at current instant.It will be like.

public class ApiRequestCodes {
public static final int apimethod[]=new int[]{Request.Method.POST,Request.Method.PUT,Request.Method.DELETE};
    public static final int requestCode_signup=1;
    public static final int requestCode_login=2;
    public static final int requestCode_addPhone=3;
    public static final int requestCode_verifyPhone=4;
   }

Step4:Create a class named as ApiManager which contain method for all types of api calls(GET,POST,PUT,DELETE).In below class AppConstants.request_Timeout=30000

public class ApiManager {
    private Context context;
    private ProgressDialog progressDialog;
    private ApiResponseInterface apiResponseInterface;
    public ApiManager(Context context, ApiResponseInterface apiResponseInterface) {
        this.context = context;
        this.apiResponseInterface = apiResponseInterface;
        progressDialog = new ProgressDialog(context);
    }

// PARAMETERS SEND IN REQUEST BODY(JSON) FORM 
 
    public void callPostApiWithRequestBody(String api_url, final Map<String, Object> params, final int requestCode, int method, final Map<String, String> headers, final boolean islastCall) {
        showDialog(context.getString(R.string.loading));
        JsonObjectRequest request = new JsonObjectRequest(method, api_url, new JSONObject(params), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                if(islastCall)
                {
                    closeDialog();
                }
                apiResponseInterface.isSuccess(jsonObject.toString(), requestCode);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                closeDialog();
                apiResponseInterface.isError(volleyError, requestCode);
            }
        }) {
            @Override
            protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                return super.parseNetworkResponse(response);
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers.size() > 0) {
                    return headers;
                }
                return super.getHeaders();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(AppConstants.request_Timeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(request);
    }
   
    public void callForOtherApi(String apiurl, final int requestCode,
                                           final Map<String, String> headers, final Map<String, String> parameters,int method,final boolean islastCall) {
        showDialog(context.getString(R.string.loading));
        StringRequest stringRequest = new StringRequest(method, apiurl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        //Disimissing the progress dialog
                        if(islastCall)
                        {
                            closeDialog();
                        }
                        apiResponseInterface.isSuccess(s, requestCode);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Dismissing the progress dialog
                        closeDialog();
                        apiResponseInterface.isError(volleyError, requestCode);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //Creating parameters
                return parameters;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers.size() > 0) {
                    return headers;
                }
                return super.getHeaders();
            }
        };
        //Creating a Request Queue
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(AppConstants.request_Timeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        //Adding request to the queue
        requestQueue.add(stringRequest);
    }
    
   
   
    /**
     * The purpose of this method is to show the dialog
     *
     * @param message
     */
    private void showDialog(String message) {
        progressDialog.setMessage(message);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }
    /**
     * The purpose of this method is to close the dialog
     */
    private void closeDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}

Now user has to finally interact with this class and get response like this.In your activity or fragment class.What you have to do is like this:

Step1: Declare the object for interface class and manager class

private ApiManager apiManager;
    private ApiResponseInterface apiInterface;

Step2: We created a method to setup whole structure named as setUpNetwork which contains instantiation for interface class and its overrided method which will capture response from interfaces including requestcode.Like this.

private void setUpNetwork()
{
    apiInterface=new ApiResponseInterface() {
        @Override
        public void isError(VolleyError volleyError,int requestcode) {
// fetching proper info from error messages using below methods
            NetworkResponse networkResponse=volleyError.networkResponse;
            if(networkResponse!=null)
            {
                Logger.LogError("STATUS_CODE",networkResponse.statusCode+"");
                String jsonError = new String(networkResponse.data);
                Logger.LogError("MESG",jsonError);
                if(jsonError.startsWith("{"))
                {
                    try {
                        JSONObject jsonObject=new JSONObject(jsonError);
                     
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                   // show messages for a type here as server didnot give improper
format data                                    
                }
            }
            else
            {
                 // show messages for a type here as server is returning null.
            }
        }
        @Override
        public void isSuccess(String response, int ServiceCode) {
              Logger.LogError("String",response);
            JSONObject jsonObject=null;
            switch (ServiceCode) {
                case ApiRequestCodes.requestCode_addPhone:
                    try {
     
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case ApiRequestCodes.requestCode_verifyPhone:
                    try {
                        jsonObject = new JSONObject(response);
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    apiManager=new ApiManager(activity,apiInterface);
}

Step3: Above all setup was to how to setUp callback in container class.Now we will get to know about how to call api.We will call suitable method using apimanager instance.First we will  create parameters and header data which we need to send with api call to validate api call.Call will be like this.

private void callConnectToServer()
{

 if(AppConstants.isInternetAvailable(activity))
{
    Map<String, Object> params = new HashMap<>();
    params.put("amount", myamount);
    Map<String,String> header=new HashMap<>();
    header.put("Authorization",sm.getLoggedUserToken());
    apiManager.callPostApiWithRequestBody(WebserviceUrl.ACCOUNTDEPOSIT_URL,params,
            ApiRequestCodes.requestCode_addPhone,ApiRequestCode.apimethod[0],header,true);
}
else
{
    Toast.makeText(activity,”Internet not available”,Toast.LENGTH_LONG).show();
}
}

In above code there is a  boolean value passed in method call.This is required when we need to do one or more api calls sequentially then to show continuous progress dialog without any stoppage we will pass true to the last api call so that progress dialog will be dismissed only after processing last call.   

 

 

 

 

 

 

 

 

 

 

 

 

 

About Author

Author Image
Keshav Gupta

Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.

Request for Proposal

Name is required

Comment is required

Sending message..