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
722 views
in Technique[技术] by (71.8m points)

json - Android/Java: how to delay return in a method

I want to build a Utils class to make Volley calls simpler, like this:

Utils.java:

public class Utils {
static JsonObjectRequest mJsonObjectRequest;    
protected static boolean busy = true;

public static JSONObject makeJsonObjectRequest(Context context, int method, String url){
    final JSONObject[] jsonObject = new JSONObject[1];
    mJsonObjectRequest = new JsonObjectRequest
            (method, url, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    jsonObject[0] = response;
                    busy = false;
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    // TODO Auto-generated method stub
                    try {
                        jsonObject[0] = new JSONObject(error.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    busy = false;
                }
            });

    // Access the RequestQueue through your singleton class.
    VolleySingleton.getInstance(context).addToRequestQueue(mJsonObjectRequest);

    while (true) {
         if (!busy) break;
    }
    return jsonObject[0];
}
}

MainActivity.java:

JSONObject jsonObject = Utils.makeJsonObjectRequest(this, Request.Method.GET, url);
mTxtDisplay.setText("Response: " + jsonObject.toString());

When app runs, jsonObject always null. I want to ask if I can delay return jsonObject[0] inside makeJsonObjectRequest until onResponse called. Can I do that and how? .

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you execute makeJsonObjectRequest on a background thread, then you can execute synchronous Volley request this way: Can I do a synchronous request with volley?

If you execute makeJsonObjectRequest on the UI thread, then you shouldn't wait for onResponse to avoid blocking UI thread. Use callback in this case.


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

...