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)))
  • 相关阅读:
    spark streaming 整合kafka(二)
    JAVA设计模式之动态代理
    使用org.apache.commons.cli包来设计JAVA命令行工具
    HTML教程
    Java InputStream和Reader
    Java IO
    程序员怎么把自己的招牌打出去?
    Java设计模式之单例模式
    JAVA NIO
    Java文件流字节流和字符流的区别
  • 原文地址:https://www.cnblogs.com/lishbo/p/9956006.html
Copyright © 2011-2022 走看看