在Volley中将响应值写入局部变量

时间:2015-10-21 06:26:31

标签: android android-volley

我是Android开发的新手,我需要帮助。我想将响应结果设置为resultDomain对象并返回。但它会以启动方式返回。

如何解决这个问题?提前谢谢。

public class NetworkController {
  public static Context context = null;
  static UserDomain resultDomain = null;
  public UserDomain login( UserDomain userDomain, Context context) {

    resultDomain = new UserDomain();
    this.context = context;
    JSONObject jsonObject = null;
    try {
        Gson gson = new Gson();
        jsonObject = new JSONObject(gson.toJson(userDomain));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    JsonObjectRequest jsonObjectRequest =
            new JsonObjectRequest(Request.Method.POST, Constant.SERVER_URL + Constant.LOGIN, jsonObject,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {

                            Gson gson = new Gson();
                            resultDomain = gson.fromJson(jsonObject.toString(), UserDomain.class);
                            Log.v("Here is Value ", resultDomain.getMessage());
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {

                    resultDomain = null;
                }
            });
    requestQueue.add(jsonObjectRequest);
    return resultDomain;
   }
}

1 个答案:

答案 0 :(得分:0)

    public class NetworkController {

    public static Context context = null;
    static UserDomain resultDomain = null;

    public void login( UserDomain userDomain, Context context,Response.Listener<JSONObject> l1, Response.ErrorListener l2) {

        resultDomain = new UserDomain();
        this.context = context;
        JSONObject jsonObject = null;
        try {
            Gson gson = new Gson();
            jsonObject = new JSONObject(gson.toJson(userDomain));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectRequest =
                new JsonObjectRequest(Request.Method.POST, Constant.SERVER_URL + Constant.LOGIN, jsonObject,
                        l1,l2);
        requestQueue.add(jsonObjectRequest);
    }



    NetworkController .login(user,context,new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jsonObject) {

            Gson gson = new Gson();
            resultDomain = gson.fromJson(jsonObject.toString(), UserDomain.class);
            Log.v("Here is Value ", resultDomain.getMessage());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {

            resultDomain = null;
        }
    });

或使用Handler