Otacilio Oliveira
Otacilio Oliveira

Reputation: 686

Execute a Volley request after another one is finished

I have two Volley requests. The first request authenticates the user; the second one gets data from the server.

If I send a GET request and the user is not authenticated, I want to fire the first request, authenticate the user and then keep executing the second one once the user is successfully authenticated.

Upvotes: 2

Views: 4635

Answers (2)

Shreyas Sanil
Shreyas Sanil

Reputation: 552

You can put one volley method inside another, as soon as the first request gets finished it sends the another request.By doing this the data will be sent to the database and the same modified data can be fetched again. The code is as shown below.

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

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

                try {
                  JSONArray genreArry = new JSONArray(response);


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

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

            }
          }) {
        @Override
        protected Map < String, String > getParams() {
          Map < String, String > params = new HashMap < String, String > ();

          return params;
        }
      };
      int socketTimeouts = 30000;
      RetryPolicy policys = new DefaultRetryPolicy(socketTimeouts, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
      stringRequests.setRetryPolicy(policys);
      RequestQueue requestQueues = Volley.newRequestQueue(context);
      requestQueues.add(stringRequests);


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

    }
  }) {
  @Override
  protected Map < String, String > getParams() {
    Map < String, String > params = new HashMap < String, String > ();

    return params;
  }
};
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);

Upvotes: 1

Otacilio Oliveira
Otacilio Oliveira

Reputation: 686

So, the solution is pretty simple. :)

After I learned about callbacks and how them work, I figured out how to do that. So, I implemented a interface that declared the methods I wanted to invoke:

public interface AuthenticationCallback {

    public void onLoginSuccess(String result);

    public void onLoginError(String result);
}

public interface ResponseCallback {

    public void onLoginSuccess(String result);

    public void onAuthorizationError(String result);

}

My function:

public void getConversationMessages(final Context context, final String conversationID, final ResponseCallback responseCallback) {

        final String url = GET_CONVERSATION_MESSAGES + conversationID;

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (responseCallback != null) {
                            responseCallback.onLoginSuccess(response);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {    
                if (error.networkResponse != null && error.networkResponse.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED){
                    if (responseCallback != null) {
                        responseCallback.onAuthorizationError(error.getMessage());
                    }
                }
            }
        })
        {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Cookie", AppSingleton.getInstance(context).getCookie());
                headers.put("Content-Type", "application/json");
                return headers;
            }
        };

        AppSingleton.getInstance(context).getRequestQueue().add(stringRequest);
    }
}

My Activity:

ServerConnection.getInstance().getConversationMessages(getApplicationContext(), id, new ResponseCallback() {
            @Override
            public void onLoginSuccess(String result) {

            }

            @Override
            public void onAuthorizationError(String result) {

                ServerConnection.getInstance().loginFunction(getApplicationContext(), userID, new AuthenticationCallback() {
                    @Override
                    public void onLoginSuccess(String result) {
                        ServerConnection.getInstance().getConversationMessages(getApplicationContext(), conID, new ResponseCallback() {
                            @Override
                            public void onLoginSuccess(String result) {

                            }

                            @Override
                            public void onAuthorizationError(String result) {

                            }
                        });
                    }
                    @Override
                    public void onLoginError(String result) {

                    }
                });
            }
        });

Basically, the code will try to send a GETrequest. If the user is not authenticated, then it will execute the code at onAuthorizationError(), that will authenticate the user. Once the user is successfully authenticate, it will send the GET request again.

I think nesting callbacks like this is not a good practice, but I'll fix it later and update my answer.

If someone have a better way to implement that, please, post another answer!

Upvotes: 2

Related Questions