代码之家  ›  专栏  ›  技术社区  ›  androidXP

如果(字符串!=空&&!String.isEmpty())不用于检查空值

  •  1
  • androidXP  · 技术社区  · 5 年前

    我正在检查字符串是否为空,但我不知道为什么它总是 if block

     Log.d(TAG,"String ID  "+str);
     if (str!= null && !str.isEmpty()){
        Log.d(TAG,"String ID is not Null ");                 
     } else {
           Log.d(TAG,"String ID is Null ");            
            }
    

    我还生成日志,在检查if条件之前检查字符串值,如下所示

    01-06 07:17:46.128 30321-30376/com.example D/### String Checker ###: Page ID  null
    01-06 07:17:46.128 30321-30376/com.example D/### String Checker ###: Page ID is not Null 
    

    更新: 将字符串设置为空,然后调用其他类似的类

    String str = null;
                new AsyncTask(searchInterfaceChat,getActivity(),String.valueOf(str)).execute(query);
    
    5 回复  |  直到 5 年前
        1
  •  3
  •   Pankaj Kumar    5 年前

    在查看日志时,字符串的值似乎为“null”。字符串不为空。看看这个。这个观察只针对你的日志


    更新代码后,问题是 String.valueOf(str) ,它正在将null转换为实际上是字符串的“null”。唯一通行证 str ,不是 字符串值(str) , 喜欢 new AsyncTask(searchInterfaceChat,getActivity(), str).execute(query);

        2
  •  3
  •   Scary Wombat    5 年前

    您正在传递字符串值 无效的 因为这将是 String.valueOf(str); 什么时候 str null

        3
  •  2
  •   Lenoarod    5 年前

    如果我们想知道,我们可以看看源代码。弦 isEmpty 如果字符串长度为零,则方法返回true。

        public boolean isEmpty() {
            // Android-changed: Get length from count field rather than value array (see above).
            // Empty string has {@code count == 0} with or without string compression enabled.
            // return value.length == 0;
            return count == 0;
        }
    
    

    方法 String.valueOf 如果对象为空,则返回“null”。

    /**
         * @return  if the argument is {@code null}, then a string equal to
         *          {@code "null"}; otherwise, the value of
         *          {@code obj.toString()} is returned.
         * @see     java.lang.Object#toString()
         */
     public static String valueOf(Object obj) {
            return (obj == null) ? "null" : obj.toString();
        }
    

    所以当您在其他类中使用它时,它返回的字符串不为空。

        4
  •  1
  •   haresh    5 年前

    为什么不使用TextUtils.isEmpty()它将检查您的两个条件。

     if (!TextUtils.isEmpty("your string")){
    Log.d(TAG,"String ID is not Null ");                 
     } else {
       Log.d(TAG,"String ID is Null ");            
        } 
    

    还要传递字符串,因为在这种情况下,您使用的是字符串类。

    尝试使用字符串s=null和s=“ad”值在两种情况下都可以正常工作:

     public class Main
     {
    public static void main(String[] args) {
     String str ="ss";
     if (str!=null&&!str.isEmpty()){
    System.out.println("not Null");               
    } else {
          System.out.println(" Null");               
        }
    }
    
        5
  •  1
  •   Md. Enamul Haque    5 年前

    无效的 首先,这样它就不会出错。

    什么时候? str 不是 null 没关系

    但是

    如果 str公司 无效的

    你还写 str!=null 它将首先尝试阅读 str公司 但它是 无效的 所以它会出错。

    if (null!=str  && !str.isEmpty()){
       Log.d(TAG,"String ID is not Null ");                 
    } else {
       Log.d(TAG,"String ID is Null ");            
    }