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

1

4

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.

Boarhound answered 3/9, 2015 at 12:11 Comment(7)
See if your requirements like this question or notDogberry
Thank Yopu, but I think that not, i would like to know how to do with some code example which is fit to my requirements.Boarhound
Actually, I still cannot understand what does your async here mean? According to Google documentation, it's async already (... with data fetched asynchronously from the network.)Dogberry
I think that async is provided by Volley automatically. So i need to know how to get JSON data into the first snippet.Boarhound
Does my answer work for your question?Dogberry
Thanks, it looks as good solution, but i don't understand what exactly means using the MySingleton class. I need some example for this.Boarhound
About the Singleton, you can refer here - Use a Singleton Pattern.Dogberry
D
8

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);
}
Dogberry answered 3/9, 2015 at 15:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.