Skip to content Skip to sidebar Skip to footer

How To Make A Volley Class A Public Method

I have to call web service in multiple classes I am using Volley. so what should I do in onresponse method to trigger the other class for the response? I want to make syncData as a

Solution 1:

Create a interface VolleyResultCallBack

publicinterfaceVolleyResultCallBack {

voidonVolleyResultListener(String response, String requestUrl);

voidonVolleyErrorListener(VolleyError error);

}

make activity implement this interface ,

your method will be like

publicstaticvoidsyncData(Context mContext, String url,VolleyResultCallBack resultCallBack) {
try {
    RequestQueue queue = Volley.newRequestQueue(mContext);

    JsonObjectRequest jsonObjectRequest = newJsonObjectRequest(Request.Method.GET, url, null, newResponse.Listener<JSONObject>() {
        @OverridepublicvoidonResponse(JSONObject response) {
            try {
                jsonResponse=response.toString();//what I should do here to trigger another class that responds achieved
               resultCallBack.onVolleyResultListener(jsonResponse,url);

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

        }
    }, newResponse.ErrorListener() {
        @OverridepublicvoidonErrorResponse(VolleyError error) {
            try {
                Log.e("Response", "error");
                resultCallBack.onVolleyErrorListener(error);
                //  updateForecastUI(isCentigradeType);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    jsonObjectRequest.setRetryPolicy(newDefaultRetryPolicy(
            Constants.MY_SOCKET_TIMEOUT_MS,
            Constants.MAX_RETRY,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    jsonObjectRequest.setShouldCache(false);
    queue.add(jsonObjectRequest);

} catch (Exception e) {
    e.printStackTrace();
}
return  jsonResponse;
}

.

In your activity make request like this

  YourClassName.syncData(this,url,this);

you will get responce in onVolleyResultListener method;

@OverridepublicvoidonVolleyResultListener(String response, String requestUrl) {

      if(requestUrl.contains(url){  //  required to check because there may be multiple requests in same activity //do something with responce
      }
    }

handle error in onVolleyErrorListener

@OverridepublicvoidonVolleyErrorListener(VolleyError error) {

 //do something with error ,may be show a toast

 }

Solution 2:

Simple, use Volley as Singleton.

So that you can hit web service in multiple classes.

your work will be done.

Post a Comment for "How To Make A Volley Class A Public Method"