android volley synchronous request code example

Example: synchronous volley request

public VolleyResponse<JSONObject> loadFutureJsonObject(String url, String keyTrack, int action, JSONObject jsonRequest, final Map<String, String> params) {

        RequestFuture<JSONObject> future = RequestFuture.newFuture();

        JsonObjectRequest request = new JsonObjectRequest(action, url, jsonRequest, future, future) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                if (params != null)
                    return params;
                return super.getParams();
            }

        };

        request.setRetryPolicy(new DefaultRetryPolicy(600000, 15, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        ApplicationController.getInstance().addToRequestQueue(request, keyTrack + Calendar.getInstance().getTimeInMillis());

        try {
            JSONObject response = future.get(2, TimeUnit.MINUTES);
            return new VolleyResponse<>(true, response);
        } catch (InterruptedException e) {
            // exception handling
            return buildErrorMessage(e.getMessage());
        } catch (ExecutionException e) {
            // exception handling
            return buildErrorMessage(e.getMessage());
        } catch (TimeoutException e) {
            // exception handling
            return buildErrorMessage(e.getMessage());
        }

    }

Tags:

Misc Example