【问题标题】:The value of the Boolean check is null at "return check"布尔检查的值在“返回检查”时为空
【发布时间】:2017-02-28 06:15:35
【问题描述】:

我在本地主机中使用 volley 连接,并且在本地主机中有一个 php 文件。下面是我的 VolleyConnectionLogin 类,我还有一个 volley 单例类(没有错误)..

public class VolleyConnectionLogin {

    Context context;
    public VolleyConnectionLogin(Context context){
        this.context = context;
    }

    static Boolean check;
    public Boolean volleyConnection(final String username , final String password) {
        String tag_string_req = "string_req";
        String url = "http://192.168.10.8/login/forlogin.php";
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d(TAG, response.toString());
                        if(response.toString().equals("successful")){
                            check = true;
                        }else{
                            check = false;
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                check = false;
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("uname", username);
                params.put("pword", password);
                return params;
            }

        };
        VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
        return check;
    }
}

【问题讨论】:

  • check 变量始终为 false,因为您在回调方法 onResponse 方法中设置了 check 变量的值。
  • static Boolean check=false; 这样使用 false 初始化检查,因为 Boolean 类型的默认值是 null

标签: php android boolean localhost android-volley


【解决方案1】:

因为您在接收响应的线程之外返回布尔值,所以这个

 Log.d(TAG, response.toString());
                        if(response.toString().equals("successful")){
                            check = true;
                        }else{
                            check = false;
                        }
                    }

在响应返回之前控制转到return check;

【讨论】:

    【解决方案2】:

    check为null,因为请求是asynchronous,所以当调用下面这行时

    VolleySingleton.getInstance(context).addToRequestQueue(stringRequest);
    

    然后程序继续到下一行

    return check; // (which is still null) 
    

    当后台的另一个线程开始处理请求时。

    您可以modify the request to be synchronous 或修改您的代码,以便根据此方法的返回,您所拥有的一切都发生在Response.Listener 回调中的onResponse() 块中。

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      • 2013-12-19
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多