提问人:Dylan 提问时间:12/23/2019 最后编辑:user1506104Dylan 更新时间:12/23/2019 访问量:96
如果我不使用 .equals 方法,我怎么会收到此错误?[关闭]
How am I getting this error if I'm not using the .equals method? [closed]
问:
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 方法,我怎么会收到此错误?
答:
0赞
mehul chauhan
12/23/2019
#1
使用这个。
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");
}
}
0赞
user1506104
12/23/2019
#2
看起来像是局部变量的默认值有问题。确保至少使用 .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");
}
}
0赞
Shahzaib Official
12/23/2019
#3
Java Compiler 不会为局部变量赋值(甚至 null)。您必须将其初始化为“Null”才能使其工作,否则 IF 语句不起作用
评论
if( "google".equals(signInMethod) )