2017-02-28 99 views
2

我在本地主机中使用排气连接,并在本地主机中有一个php文件。下面是我的课VolleyConnectionLogin和我也有一个凌空单身类(没有错误)..在“返回检查”时布尔检查的值为空

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; 
    } 
} 
+0

'check'变量总是为false,因为您正在使用回调方法'onResponse'方法设置'check'变量的值。 –

+0

使用false来初始化检查,例如'static Boolean check = false;',因为'Boolean'类型的默认值为'null'。 –

回答

1

check为null,因为该请求是asynchronous,所以当以下行被称为

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

该程序然后前进到下一行是

return check; // (which is still null) 

而背景另一个线程开始处理该请求。

您可能会modify the request to be synchronous或修改您的代码,以便取决于此方法的返回取决于发生onResponse()Response.Listener回调中的代码。

1

,因为你正在返回你的线程在其接收响应的布尔外,这一个

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

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