一尘不染

Android / Java:如何延迟返回方法

json

我想构建一个Utils类,以使Volley调用更简单,如下所示:

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

当应用运行时,jsonObject始终为null。我想问一下是否可以延迟在makeJsonObjectRequest中返回jsonObject
[0]直到调用onResponse。我可以这样做吗?。


阅读 376

收藏
2020-07-27

共1个答案

一尘不染

我创建了此文件,并按照以下方式进行管理,请看一下,希望对您有用

public class APIManager {



    public static void createRequest(Context c, String requestTag,
            String endPoint, List<NameValuePair> params,
            final OnRequestCompletedListener listener,
            TransParentProgressDialog pd) {
        ServerDetails serverDetails = new ServerDetails(c, endPoint, params);
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                serverDetails.getQueryUrl(), null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        listener.onRequestCompleted(response);
                    }
                }, getErrorListener(c, pd)) {

        };
        AppController.getInstance().addToRequestQueue(request, requestTag);
    }

public static ErrorListener getErrorListener(final Context c,
            final TransParentProgressDialog pd, final TextView tvEmpty,
            final String errorText) {

        Response.ErrorListener listener = new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (pd != null && pd.isShowing()) {
                    pd.dismiss();
                }
                if (tvEmpty != null) {
                    tvEmpty.setText(errorText);
                }
                MyDialog dialog;
                Log.d("volley-error", error.toString());

                if (error instanceof TimeoutError) {
                    dialog = new MyDialog(c, "Server Timeout");
                    dialog.show();
                    return;
                } else if (error instanceof NoConnectionError) {
                    dialog = new MyDialog(c, "No Connection or Invalid Url");
                    dialog.show();
                    return;

                } else if (error instanceof ServerError) {
                    NetworkResponse response = error.networkResponse;
                    if (response != null) {
                        // int statusCode = response.statusCode;
                        byte[] data = response.data;
                        if (data != null) {
                            String str = new String(data);
                            try {
                                JSONObject object = new JSONObject(str);
                                Log.d("error response", object.toString());
                                if (object.has("errors")) {
                                    JSONArray errors = object
                                            .getJSONArray("errors");
                                    JSONObject errorObject = errors
                                            .getJSONObject(0);
                                    dialog = new MyDialog(c, "Error!",
                                            errorObject.getString("message"));
                                    dialog.show();
                                } else {
                                    dialog = new MyDialog(c, "Error!",
                                            object.toString());
                                    dialog.show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                dialog = new MyDialog(c, "Error!", "Error");
                                dialog.show();
                            }
                        } else {
                            dialog = new MyDialog(c, "Server Error");
                            dialog.show();
                        }
                    } else {
                        dialog = new MyDialog(c, "Server Error");
                        dialog.show();
                    }

                } else if (error instanceof NetworkError) {
                    NetworkResponse response = error.networkResponse;
                    if (response != null) {
                        // int statusCode = response.statusCode;
                        byte[] data = response.data;
                        if (data != null) {
                            String str = new String(data);
                            try {
                                JSONObject object = new JSONObject(str);
                                Log.d("error response", object.toString());
                                if (object.has("errors")) {
                                    JSONArray errors = object
                                            .getJSONArray("errors");
                                    JSONObject errorObject = errors
                                            .getJSONObject(0);
                                    dialog = new MyDialog(c, "Error!",
                                            errorObject.getString("message"));
                                    dialog.show();
                                } else {
                                    dialog = new MyDialog(c, "Error!",
                                            object.toString());
                                    dialog.show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                dialog = new MyDialog(c, "Error!", "Error");
                                dialog.show();
                            }
                        } else {
                            dialog = new MyDialog(c, "Network Error");
                            dialog.show();
                        }
                    } else {
                        dialog = new MyDialog(c, "Network Error");
                        dialog.show();
                    }
                } else if (error instanceof ParseError) {
                    dialog = new MyDialog(c, "Parse Error");
                    dialog.show();
                } else if (error instanceof AuthFailureError) {
                    NetworkResponse response = error.networkResponse;
                    if (response != null) {
                        // int statusCode = response.statusCode;
                        byte[] data = response.data;
                        if (data != null) {
                            String str = new String(data);
                            try {
                                JSONObject object = new JSONObject(str);
                                Log.d("error response", object.toString());
                                if (object.has("errors")) {
                                    JSONArray errors = object
                                            .getJSONArray("errors");
                                    JSONObject errorObject = errors
                                            .getJSONObject(0);
                                    dialog = new MyDialog(c, "Error!",
                                            errorObject.getString("message"));
                                    dialog.show();
                                } else {
                                    dialog = new MyDialog(c, "Error!",
                                            object.toString());
                                    dialog.show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                dialog = new MyDialog(c, "Error!", "Error");
                                dialog.show();
                            }
                        } else {
                            dialog = new MyDialog(c, "Error!", "Error");
                            dialog.show();
                        }
                    } else {
                        dialog = new MyDialog(c, "Error connecting server");
                        dialog.show();
                    }
                }
            }
        };
        return listener;
    }
}

并按要求完成回叫的界面是

public interface OnRequestCompletedListener {

        public void onRequestCompleted(JSONObject response);
    }
2020-07-27