Android:无法检查字符串变量是否为null。如何检查字符串变量是否为null?

时间:2014-04-17 06:21:31

标签: java string

我无法检查字符串是否为空或者是否来自休息服务作为输入流,然后我将其更改为字符串以进行解析。

public boolean isNullorEmpty(String string)
  {
   if(string !=null || !string.isEmpty() || string.length()>0)
    return true;
   else
    return false;
 }

请帮我检查字符串是否为空。

2 个答案:

答案 0 :(得分:1)

代码中的当前问题是,如果您在参数中传递的字符串为null,则string !=null将评估为false。因此,您将尝试评估!string.isEmpty(),这将导致NullPointerException

另一方面,如果您传递的字符串不是null(ex """test"),则string != null会被评估为true,因此您返回{{ 1}}。

所以要修复你应该,正如你的方法名称所暗示的那样,检查String是否为空或空。

但是既然你已经开始使用android了,请不要重新发明轮子并使用TextUtils.isEmpty(CharSequence str)

true
  

如果字符串为null或0-length,则返回true。

如果你想了解它是如何实现的:

boolean isEmpty = TextUtils.isEmpty(myString);

答案 1 :(得分:0)

嗯,这可以在普通的java中处理,如:

它可以写成:

public boolean isStringEmpty (){
    if(str ==null || str.isEmpty () || str.trim().equals("")){
        return true;
    }
    return false;
}
相关问题