在阅读之前,我是一个尝试学习android开发的新手,请不要对我加倍努力。
我有这个实时数据库firebase:
我正在尝试检查所输入的电子邮件是否存在,我尝试了一种方法,但对我来说不起作用。
我尝试了这种方法:
private boolean checkIfExistes() {
reference.child("Users").orderByChild("email").equalTo(Email.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
CheckExists =true;
else
CheckExists =false;
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
if (CheckExists)
return true;
else
return false;
}
即使电子邮件存在,它也始终返回false。请帮助。
答案 0 :(得分:0)
private DatabaseReference rootRef,userRef;
通过oncreare方法获取初始化firebase
rootRef = FirebaseDatabase.getInstance().getReference();
userRef = rootRef.child("Users");
此处用于检查电子邮件的代码是否存在
userRef.orderByChild("email").equalTo(emailEdt.getText().toString())
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
hideProgress();
if (dataSnapshot.exists()){
Toast.makeText(LoginActivity.this,"User already exists",Toast.LENGTH_SHORT).show();
}else {
UserLogin user = new UserLogin(emailEdt.getText().toString(),profilePath);
DatabaseReference db = userRef.push();
db.setValue(user);
//Log.d(TAG,"user key is::: "+db.getKey());
prefs.savEmail(emailEdt.getText().toString());
prefs.savProfileUrl(profilePath);
prefs.savKey(db.getKey());
openMainActivity();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
hideProgress();
Toast.makeText(LoginActivity.this,databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
});
答案 1 :(得分:0)
尝试一下:
boolean CheckExists =false; //declare and assign default value in global scope
reference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> userChildren = dataSnapshot.getChildren();
for (DataSnapshot user: userChildren) {
User u = user.getValue(User.class); //make a model User with necessary fields
if(u.email.equalsIgnoreCase(Email.getText().toString())){
CheckExists =true;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});