【问题标题】:Checking null String in android在android中检查空字符串
【发布时间】:2013-10-04 15:16:58
【问题描述】:

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

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

但是如果我们的值为'null',则控件不会进入else部分

请给我一个解决方案。

提前致谢。

【问题讨论】:

  • 你有空字符串文字吗?那么你需要试试 !cell.equals("null");

标签: java android string


【解决方案1】:

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

我会说

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

【讨论】:

    【解决方案2】:

    不是equals(null)

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

    【讨论】:

      【解决方案3】:
      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

          使用这个:

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

          【讨论】:

            【解决方案7】:

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

            TextUtils.isEmpty(<<stringVariable>>);
            

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

            【讨论】:

              【解决方案8】:

              工作!!!

               if (string.matches("")&& string.trim().equals("null")){
              
                  return false;
              }
              else{
                  return true;
              }
              

              【讨论】:

                猜你喜欢
                • 2015-01-21
                • 2014-07-30
                • 1970-01-01
                • 1970-01-01
                • 2016-08-14
                • 1970-01-01
                • 2013-04-29
                • 1970-01-01
                • 2011-04-01
                相关资源
                最近更新 更多