Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to return async JSONObject from method using Volley?

I'm trying to get back JSON object in the following way:

JSONObject jsonObject = http.makeRequest("GET", "https://api.twitter.com/1.1/search/tweets.json", null);

General method for processing all HTTP requests is following

public void makeRequest(String method, String url, Array params) {

    // Request a string response from the provided URL.
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(getRequestMethod(method),
            url,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    processResponse(Constants.Global.SUCCESS, null, response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    try {
                        mStatusCode = error.networkResponse.statusCode;
                        VolleyLog.d(Constants.Global.ERROR, "Error: " + error.getMessage());
                        Logger.e(error.getMessage());
                    } catch (Exception e) {
                        Logger.e(e.getMessage());
                        mStatusCode = 0;
                    }
                    Logger.e(mStatusCode.toString());
                    processResponse(Constants.Global.ERROR, mStatusCode, null);
                }
            });
    // Add tag to request for bulk cancelling
    //jsonObjReq.setTag()
    queue.add(jsonObjReq);
}

And method for processing JSON result is following:

private JSONObject processResponse(String resultState, Integer httpStatusCode, JSONObject responseData) {
        try {
            // First check that result state is error or the success
            if (resultState.equals(Constants.Global.SUCCESS)) {
                Logger.i("Response is success");
                Logger.i(responseData.toString());
                //TODO: ADD SUCCESS OBJECT CREATION
            }
            if (resultState.equals(Constants.Global.ERROR)) {
                Logger.e("Response is error");
                //TODO: ADD ERROR HANDLING AND ERROR OBJECT CREATION
            }

        } catch(Exception e) {
            e.printStackTrace();
            Logger.e(e.getMessage());
        }
        return responseData;
    }

I would like to ask how can i to get back JSONObject (first code snippet) in the async way.

All requests are processed using the Volley library.

Many thanks for any advice.

like image 377
redrom Avatar asked Feb 10 '23 03:02

redrom


1 Answers

For your comment

I think that async is provided by Volley automatically. So i need to know how to get JSON data into the first snippet

IMO, instead of your first snippet, you can try the following way (of course, you can replace JSONArray request by JSONObject request):

VolleyResponseListener listener = new VolleyResponseListener() {
            @Override
            public void onError(String message) {
                // do something...
            }

            @Override
            public void onResponse(Object response) {
                // do something...
            }
        };

makeJsonArrayRequest(context, Request.Method.POST, url, requestBody, listener);

Body of makeJsonArrayRequest can be as the following:

    public void makeJsonArrayRequest(Context context, int method, String url, String requestBody, final VolleyResponseListener listener) {
        JSONObject jsonRequest = null;        
        try {
            ...
            if (requestBody != null) {
                jsonRequest = new JSONObject(requestBody);
            }
            ...
        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(method, url, jsonRequest, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                listener.onResponse(jsonArray);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error.toString());
            }
        });

        // Access the RequestQueue through singleton class.
        MySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
    }

VolleyResponseListener interface as the following:

public interface VolleyResponseListener {
    void onError(String message);

    void onResponse(Object response);
}
like image 102
BNK Avatar answered Feb 12 '23 09:02

BNK