简体   繁体   中英

Android Java exception even after string null or empty check

I really don't understand why java.lang.NumberFormatException: Invalid long: "null" happens here.

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)); 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 .

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".

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

Also, in your case, check that userid does not contain the "null" String

Moreover userid.equals("") and userid.isEmpty() are the same thing.

You can check null with utility method isEmpty from TextUtils ,

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

isEmpty(CharSequence str) method check both condition, for null and length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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