使用TextUtils.isEmpty()遇到的坑

使用TextUtils.isEmpty()遇到的坑

Android开发中,我们经常使用TextUtils.isEmpty()来判断字符串是否为null或者空字符串,防止出现空指针异常,有一天执行报出了空指针异常 。如下

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference

满头黑线

查看源码

   /**
     * 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;
    }

得出一般情况下使用是没问题的。
现在我们考虑这样一种情况:假设实体参数有一个属性name,String类型。后台在响应这个属性到手机端的时候,是这样赋值的name = null + “”,这样就会报错。

安全写法

!((TextUtils.isEmpty(name)) && ("null".equalsIgnoreCase(name)))
发布了46 篇原创文章 · 获赞 35 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/sinat_27672523/article/details/88873677