zoukankan      html  css  js  c++  java
  • 使用TextUtils.isEmpty()遇到的坑

    Android开发中,我们经常使用TextUtils.isEmpty()来判断字符串是否为null或者空字符串,防止出现空指针异常,但是之前使用这个方法的时候,出现了一点小问题,所以记录下来,防止以后再犯。

    TextUtils.isEmpty()的实现如下:

        /**
         * Returns true if the string is null or 0-length.
         * @param str the string to be examined
         * @return true if str is null or zero length
         */
        public static boolean isEmpty(CharSequence str) {
            if (str == null || str.length() == 0)
                return true;
            else
                return false;
        }

    一般情况下使用是没问题的。
    现在我们考虑这样一种情况:假设实体Student有一个属性name,String类型。后台在响应这个属性到手机端的时候,是这样赋值的name = xxx + “”,这样可以防止name属性为null,但是如果xxx为null,响应的name是什么样的呢?我们测试一下。
    null字符串

    响应过来的其实是字符串“null”,这样我们再使用TextUtils.isEmpty()进行非空判断的时候,就会出错,遗漏掉一种情况。健全的判断方法应该是:

    !((TextUtils.isEmpty(name)) && ("null".equalsIgnoreCase(name)))
  • 相关阅读:
    WebStorm使用Vue
    hive的简单操作
    hbase的简单操作
    CentOS 7 配置hadoop(五) 配置sqoop(伪分布)
    CentOS7配置hadoop集群
    CentOS 7 配置hadoop(四) 配置hive(伪分布)
    CentOS 7 配置hadoop(三) 配置hbase(伪分布)
    五种变量创建的方法
    GO练习题
    第一次作业总结
  • 原文地址:https://www.cnblogs.com/lishbo/p/9956006.html
Copyright © 2011-2022 走看看