空检查无效

时间:2014-06-02 08:23:19

标签: java android

抱歉,如果这是一个低质量的问题,但仍然是一个问题:)这里我使用一个简单的眼睛条件检查EditText' s null存在,

public String theuser=null;
public String thepass=null;

EditText  u=(EditText)findViewById(R.id.inputuser);
this.theuser = u.getText().toString();
EditText p =(EditText)findViewById(R.id.inputpassword);
this.thepass = p.getText().toString();

if ((theuser.equals(null))||(thepass.equals(null))){ 
    Toast.makeText(this,"Username and Password Cant Be Empty!",     
    Toast.LENGTH_SHORT).show();   
}else{
    Log.i("lifemate","did you click me ?!"+theuser+"  "+thepass);
    BusProvider.getInstance().post(SendRequestInfo());
}

但是空检查似乎无法正常工作!我试过.equals(null)和.equals("")仍然无法正常工作!伙计们知道为什么会这样吗?!

6 个答案:

答案 0 :(得分:3)

应使用null运算符与==进行比较。

所以请使用if (theuser==null || thepass == null)

答案 1 :(得分:2)

这  if ((theuser.equals(null))||(thepass.equals(null))){

必须是 if ((theuser.equals(""))||(thepassequals(""))){

因为如果没有输入,getText()会返回一个空字符串。它不会返回null。

答案 2 :(得分:0)

equals null不适用于String对象的引用。

您需要使用(mystring != null)来测试可空性。

答案 3 :(得分:0)

替换

if ((theuser.equals(null))||(thepass.equals(null)))

if (theuser==null||thepass==null)

答案 4 :(得分:0)

Equals contract声明:

  

对于任何非空引用值x,x.equals(null)应返回false。

但当xnull时,这会导致NullPointerException,因为您正在尝试访问null对象的方法。

简而言之,使用x == null而不是x.equals(null)

但在你的情况下

您正在测试TextView中的文本值。我不希望这是null,特别是在toString()上拨打CharSequence时。所以如果有的话,这将是空的,即你可以这样做:

if ("".equals(theuser) || "".equals(thepass)) {

答案 5 :(得分:0)

为了检查字符串中的null,android提供非常好的类

你只需在

中传递你的字符串
//check while for the null string. 
if(TextUtils.isEmpty("YOUR_STRING")){
 //perform operation. 
}

它将自动处理NULL以及EMPTY字符串。