如果我不使用.equals方法,该如何得到此错误?

时间:2019-12-23 10:50:32

标签: java android nullreferenceexception

String signInMethod;
...

...
if (signInMethod != null) {
    if (signInMethod.equals("google")) {
        intent.putExtra("signInMethod", "google");
    } else if (signInMethod.equals("email")) {
        intent.putExtra("signInMethod", "email");
    }
} else {
    intent.putExtra("signInMethod", "alreadySignedIn");
}
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference

如果我不使用.equals方法,如何得到此错误?

enter image description here

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:0)

使用它。

  String signInMethod = null;
    if(TextUtils.isEmpty(signInMethod)){
        Toast.makeText(context, "Some thing wrong please try again", Toast.LENGTH_SHORT).show();
    }else {
        if (signInMethod.equalsIgnoreCase("google")) {
            intent.putExtra("signInMethod", "google");
        } else if (signInMethod.equalsIgnoreCase("email")) {
            intent.putExtra("signInMethod", "email");
        } else {
            intent.putExtra("signInMethod", "alreadySignedIn");
        }
    }

答案 1 :(得分:0)

看起来像局部变量的默认值有问题。确保至少用signInMethod初始化null

public void myMethod() {
    String signInMethod = null; // <--- THE FIX
    ...

    ...
    if (signInMethod != null) {
        if (signInMethod.equals("google")) {
            intent.putExtra("signInMethod", "google"); 
        } else if (signInMethod.equals("email")) {
            intent.putExtra("signInMethod", "email");
        }
    } else {
        intent.putExtra("signInMethod", "alreadySignedIn");
    }
}

答案 2 :(得分:0)

Java编译器不会将任何值(甚至为null)分配给局部变量。您必须将其初始化为“ Null”以使其起作用,否则 IF 语句不起作用