Nick
Nick

Reputation: 2948

Delete requests remaining in the Queue after CancelAll

In the code below after the CancelAll and Stop, the request that added afterwards in the queue, will be immediately execute after the start command.

How can i remove the last request/requests that was inserted in queue?

    final  RequestQueue queue = Volley.newRequestQueue(this);
    String url ="";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    Log.d("response", response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("VolleyError", error.toString());
        }
    });

    // Add the request to the RequestQueue.

    stringRequest.setTag("a");
    queue.cancelAll("a");
    queue.stop();
    queue.add(stringRequest);
    queue.start();

Upvotes: 1

Views: 829

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

As you queue reference is a local variable so you need to move it outside and since you are using it in activity so declare it like

private RequestQueue queue;

..oncreate(..){
    //... code
    queue = Volley.newRequestQueue(this);
}

and create a separate method to cancel all requests as

void cancelAllQueuedRequests(){
    queue.cancelAll("a");
    queue.stop();
    queue.start();
}

call cancelAllQueuedRequests wherever you want and add requests like this

String url ="some url";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.d("response", response);
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d("VolleyError", error.toString());
        cancelAllQueuedRequests();
    }
});

// Add the request to the RequestQueue.

stringRequest.setTag("a");
queue.add(stringRequest);
//queue.start(); no need

Upvotes: 1

Related Questions