我正在尝试为我的应用创建日志记录活动。所以我使用了firebase。但是现在我想举杯说当我插入已经存在的电子邮件时,但我发现这样做很困难。这就是我所做的:
public void checkEmailExistsOrNot(){
fAuth.fetchSignInMethodsForEmail(eml).addOnCompleteListener(new OnCompleteListener<SignInMethodQueryResult>() {
@Override
public void onComplete(@NonNull Task<SignInMethodQueryResult> task) {
if (task.getResult().getSignInMethods().size() == 0){
exist = false;
}else {
exist = true;
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
}
});
}
这里我检查布尔值是否等于真(因此电子邮件已经存在,我不继续注册)或者如果是,则电子邮件不存在,所以我继续注册:
checkEmailExistsOrNot();
if (exist) {
Toast.makeText(getApplicationContext(), "Email giá registrata", Toast.LENGTH_SHORT);
return;
} else {
fAuth.createUserWithEmailAndPassword(eml, passw).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
progress.setVisibility(View.GONE);
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "registration made", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "registration not performed", Toast.LENGTH_SHORT).show();
}
}
});
}
问题是,即使我插入已经存在的电子邮件,exist 变量仍然是 false,因此程序尝试创建一个帐户,如果没有这样做,它会提示没有注册。怎么解决?
答案 0 :(得分:0)
这里的问题是 fetchSignInMethodsForEmail
是异步的,但您将其称为同步。将您的函数转换为返回 true
或 false
的 Future / async 调用。否则,您的代码会在不等待 onComplete
的情况下继续,因此该值始终为 false
。
答案 1 :(得分:0)
Firebase 会自动告诉您要创建帐户的电子邮件是否已经存在。 创建帐户时,您应该检查任务是否成功
if(task.isSuccessful()) {} // you have this code in your last bit of code
else{} // you have this in your code already
(
您当前拥有代码
Toast.makeText(getApplicationContext(), "registration not performed", Toast.LENGTH_SHORT).show();
(它几乎是您提供的代码中的最后一行)但您应该将其替换为:
try {
throw task.getException();
} catch(FirebaseAuthUserCollisionException e) {
// email already in use
Toast.makeText(getApplicationContext(), "Email already taken!", Toast.LENGTH_SHORT).show();
}
因此您不需要自己检查电子邮件是否存在,因为 Firebase 会自动抛出异常,然后您可以例如显示吐司。