简体   繁体   English

即使字符串null或空检查后,Android Java异常

[英]Android Java exception even after string null or empty check

I really don't understand why java.lang.NumberFormatException: Invalid long: "null" happens here. 我真的不明白为什么java.lang.NumberFormatException:无效长:这里发生“空”。

The problem snippet is like followings. 问题片段如下。

try {
        userid = ((JSONObject) msg.obj).getString("userid");
        if (userid.equals("") || userid.isEmpty() || null==userid) {
                onClickLogout();
                return;
        } else {
            client.setUserid(Long.parseLong(userid));
       }
    } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            onClickLogout();
            return;
    }

the line client.setUserid(Long.parseLong(userid)); 行client.setUserid(Long.parseLong(userid)); gets following exception 得到以下异常

java.lang.NumberFormatException: Invalid long: "null"
at java.lang.Long.invalidLong(Long.java:125)
at java.lang.Long.parse(Long.java:362)
at java.lang.Long.parseLong(Long.java:353)
at java.lang.Long.parseLong(Long.java:319)
at client.setUserid(Long.parseLong(userid));

The point is that the null exception occurs even after null and empty check of the userid in the code. 关键是即使在对代码中的用户标识进行空值和空值检查之后,也会发生空异常。 What's wrong with me here? 我这是怎么了 please check it out experts! 请检查出专家!

The string value and not reference is null . 字符串 (非引用)为null

You can add "null".equals(userid) to test for the literal null value in the if where you check for various forms of "no value". if检查各种形式的“无值”, if可以添加"null".equals(userid)来测试文字null值。

Always check first for null value in your condition 始终先检查您的情况是否为空值

if (null==userid || userid.isEmpty() || userid.equals("null") {

Then, in the next element of your condition, you are sure that userid is not null and no NullPointerException will be thrown 然后,在条件的下一个元素中,确保userid不为null,并且不会引发NullPointerException

Also, in your case, check that userid does not contain the "null" String 另外,在您的情况下,请检查userid是否不包含“ null”字符串

Moreover userid.equals("") and userid.isEmpty() are the same thing. 而且userid.equals("")userid.isEmpty()是同一件事。

You can check null with utility method isEmpty from TextUtils , 您可以使用TextUtils实用程序方法isEmpty检查null

public static boolean isEmpty(CharSequence str) {
     return str == null || str.length() == 0;
}

isEmpty(CharSequence str) method check both condition, for null and length. isEmpty(CharSequence str)方法检查两个条件,是否为null和length。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM