Java 在android中检查空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19184854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:52:32  来源:igfitidea点击:

Checking null String in android

javaandroidstring

提问by Sundeep

I am developing an android application.I am getting a String value as null from webservice. I am fetching the value and storing it in a String variable. Then when I print the value using Log, like Log.i("tag", "````!!!cell >>"+cell);, I an getting null printed in the screen. Now what i need is that I need to check the variable for 'null' and I want to display a textfield with no value if it is 'null'. I am using the following statement for checking

我正在开发一个 android 应用程序。我从 webservice 获取一个 String 值作为 null。我正在获取值并将其存储在一个字符串变量中。然后,当我使用 Log 打印值时,如 Log.i("tag", "````!!!cell >>"+cell);,我在屏幕上打印了一个空值。现在我需要的是我需要检查变量是否为“空”,如果它为“空”,我想显示一个没有值的文本字段。我正在使用以下语句进行检查

if(!cell.equals(null) || !cell.equals("")) {
  _______
} else {
  _______
}

But the control is not going inside the else part if the value us 'null'

但是,如果值 us 'null',则控件不会进入 else 部分

Please give me a solution.

请给我一个解决方案。

Thanks in advance.

提前致谢。

回答by tyczj

its not equals(null)its

它不是equals(null)它的

if(cell != null || !cell.isEmpty())

回答by Vandesh

If the value of the string is null, !cell.equals("")will evaluate to true and hence it will go in the if part and not the else part as you are using an OR condition.

如果字符串的值为空,!cell.equals("")将评估为真,因此它将进入 if 部分而不是 else 部分,因为您正在使用 OR 条件。

NULL != "" (Empty string)!!!

NULL != ""(空字符串)!!!

回答by Suresh Atta

when cellis null , and you are trying to invoke a method on it, you will hit by a null pointer exception.

cell为 null 时,并且您尝试对其调用方法时,您将遇到空指针异常。

I'd say

我会说

if(cell !=null  &&  !cell.isEmpty()) {
  _______yes, disply
} else {
  _______nope, some thing wrong
}

回答by Rat-a-tat-a-tat Ratatouille

Use this :

用这个 :

if (cell != null && cell.trim().length() > 0) {
    // do whatever you want
} else {
    // the string received is null
}

回答by Nabdreas

I would give try this, seems to be working for me!

我会试试这个,似乎对我有用!

if(TextUtils.isEmpty(yourString) && yourString == null){

}
else if(!TextUtils.isEmpty(yourString) && yourString != null){

}

回答by Rams_QA

Android provides a simple utility

Android 提供了一个简单的实用程序

TextUtils.isEmpty(<<stringVariable>>);

More details @ http://developer.android.com/reference/android/text/TextUtils.html

更多详情@ http://developer.android.com/reference/android/text/TextUtils.html

回答by Salman Nazir

WORKING !!!

在职的 !!!

 if (string.matches("")&& string.trim().equals("null")){

    return false;
}
else{
    return true;
}