用户身份验证后,我在Firebase数据库中创建了用户节点和IsRegistrationCompleted
变量。然后我将检查传递给EventMainActivity
,我做的第一件事就是检查IsRegistrationCompleted
值。
我遇到的问题是,当我切换到EventMainActivity
系统尚未完成将数据插入FirebaseDatabase并且没有找到值IsRegistrationCompleted
时,系统会出错。
这是我的代码:
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
isNew = task.getResult().getAdditionalUserInfo().isNewUser();
if(isNew) {
prefManager.setIsFirstAccess(true);
addUserToDb(user);
}
} else {
..
}
..
}
});
}// [END auth_with_google]
...
//在Firebase数据库中添加用户
private void addUserToDb(FirebaseUser user) {
uid = user.getUid();
author.setUid(uid);
author.setEmail(user.getEmail());
author.setFull_name(user.getDisplayName());
author.setUrl_img_profile_large(user.getPhotoUrl().toString());
userRef = rootRef.child("Users").child(uid);
userRef.setValue(author).addOnCompleteListener(this,new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()) {
setRegistrationNotCompleted();
}
}
});
}
//在FirebaseDatabase中插入IsRegistrationCompleted
private void setRegistrationNotCompleted() {
user_registration = rootRef.child("Users_Settings").child(uid).child("IsRegistrationCompleted");
user_registration.setValue(NOT_REG).addOnCompleteListener(this,new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
startActivity(newIntent(RegActivity.this,EventMainActivity.class));
finish();
}
}
});
}
此时,输入EventMainActivity我发现java.lang.NullPointerException,因为它找不到变量IsRegistrationCompleted,实际上在firebase数据库中还没有插入值。
//尝试异常时这是代码
usr_registration.child(uid).child("IsRegistrationCompleted").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Boolean isRegCompleted =(Boolean) dataSnapshot.getValue();
Log.d(TAG,"isRegcompleted "+isRegCompleted);//Here in the Log there is "isRegcompleted null"
if (isRegCompleted.equals(false)) {
launchWizardReg();
}
}
答案 0 :(得分:2)
在值事件侦听器中添加存在的检查以避免空值,因为在节点上按firebase设置值可能需要一些时间。
usr_registration.child(uid).child("IsRegistrationCompleted")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Boolean isRegCompleted =(Boolean) dataSnapshot.getValue();
Log.d(TAG,"isRegcompleted "+isRegCompleted);
if (isRegCompleted.equals(false)) {
// remember to remove the value event listener,
//else it will be called again if the value changes
launchWizardReg();
}
}
}
由于您正在使用值事件侦听器而不是单值事件,因此如果值在此节点处发生更改,它将继续触发,因此在需要的值可用时删除侦听器