今天在騰訊Buggly中查看我司APP錯(cuò)誤日志時(shí)發(fā)現(xiàn)這么一個(gè)錯(cuò)誤:
Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference com.zjelite.login.utils.WebKeyUtils$4.handleMessage(WebKeyUtils.java:354)
追了下代碼,發(fā)現(xiàn)是因?yàn)樵趯?duì)字符串判斷非空的時(shí)候使用了 java中String類下的isEmpty(),而不是android 中的TextUtils.isEmpty( )。詳細(xì)原因如下:
java中,String 類下的 isEmpty( ) 返回的只是 字符串的長(zhǎng)度是否為0,如果 字符串為null 就會(huì)直接報(bào)空指針。源碼如下:
public boolean isEmpty() { return count == 0; }
android中,TextUtils.isEmpty(要判斷的字符串) 會(huì)對(duì) null 和長(zhǎng)度進(jìn)行判斷,所以不會(huì)報(bào)空指針。源碼如下:
public static boolean isEmpty(@Nullable CharSequence str) { if (str == null || str.length() == 0) return true; else return false; }