Android Volley multiple Requests
Asked Answered
S

3

6

I try to execute a new volley request in the current volley request, but when the new request is called it don't step into the onrespond method.

The new request should be executed before the first ends. (Last in, first out)

How can I execute the new request succesfully ?

private void makeJsonObjectRequest() {
    ac = new AppController();


    final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d("test", response.toString());

            try {
                // Parsing json object response
                // response will be a json object


                JSONArray name = response.getJSONArray("data");
                for (int i = 0; i < name.length(); i++) {
                    JSONObject post = (JSONObject) name.getJSONObject(i);

                    try {
                        objectid = post.getString("object_id");

                        newRequest(objectid);

                    }
                    catch (Exception e) {

                   }

                }


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

            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("test", "Error: " + error.getMessage());
        }
    });

    // Adding request to request queue
    ac.getInstance().addToRequestQueue(jsonObjReq);
}
Sputum answered 17/6, 2015 at 13:57 Comment(1)
set Priority.HIGH to inner request and Priority.LOW to outer requestPlasmosome
P
3

Try it Work 100%

public class Utility {
String result = "";

String tag_string_req = "string_raq";
private Activity activity;
Context context;
private LinearLayout mLinear;
private ProgressDialog pDialog;
public Utility(Context context) {
    this.context = context;
}

public String getString(String url, final VolleyCallback callback) {
    showpDialog();
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            result = response;
            hideDialog();
            callback.onSuccess(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            callback.onRequestError(error);
            hideDialog();
           /*LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            View layout = inflater.inflate(R.layout.custom_toast, null);
            ((Activity) context).setContentView(layout);*/

        }
    });
    VolleySingleton.getInstance().addToRequestQueue(stringRequest, tag_string_req);
    stringRequest.setRetryPolicy(
            new DefaultRetryPolicy(1 * 1000, 1, 1.0f));
    return result;
}

public interface VolleyCallback {
    void onSuccess(String result);
    void onRequestError(VolleyError errorMessage);
    //void onJsonInvoke(String url, final VolleyCallback callback);
}

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

private void showpDialog() {
    onProgress();
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}

public void onProgress() {
    pDialog = new ProgressDialog(context);
    pDialog.setMessage("Please wait...");
    pDialog.setCancelable(false);
    pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
}

}

Call Fragment

Utility utility = new Utility(getContext());
    utility.getString(urls, new Utility.VolleyCallback() {
        @Override
        public void onSuccess(String result) {
            try {
                JSONObject toplinks = new JSONObject(result);
                JSONObject data  = toplinks.getJSONObject("toplinks");
                M.i("============LS", "" + data);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            finally {

            }
        }
        @Override
        public void onRequestError(VolleyError errorMessage) {
            errorJson.setVisibility(View.VISIBLE);
            String msg = VolleyException.getErrorMessageFromVolleyError(errorMessage);
            errorJson.setText(msg);
        }
    });
Piker answered 27/1, 2016 at 12:28 Comment(1)
This looks good with one request. In my case I have 5 requests to be performed but the first one must be completed before the next 4 requests. The next 4 requests can go in parallel. Any suggestions, how can I achieve that?Godred
E
0

all this about

Request Prioritization

Networking calls is real time operation so let consider we have multi request like in your case , Volley processes the requests from higher priorities to lower priorities , in first-in-first-out order.

So all you need change priority (set Priority.HIGH) to request you want process first.

here is a piece of code

public class CustomPriorityRequest extends JsonObjectRequest {

// default value
    Priority mPriority = Priority.HIGH;

    public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(method, url, jsonRequest, listener, errorListener);
    }

    public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
        super(url, jsonRequest, listener, errorListener);
    }

    @Override
    public Priority getPriority() {
        return mPriority;
    }

    public void setPriority(Priority p){
        mPriority = p;
    }
}
Electrocardiograph answered 9/12, 2015 at 14:46 Comment(0)
P
0

As others mentioned one way is to put a high priority on the request.

Another option as it seems you have the first request depending on the inner one wrapped in the try-catch block which seems to me you want to achieve a synchronous/blocking behavior for this specific case. then you can use RequestFuture :

RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = newRequest(objectid, future);
requestQueue.add(request);
String result = future.get();
Per answered 29/3, 2016 at 21:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.