Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

json - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...