我正在使用firebase auth ui来创建具有邮件和密码的用户,但在注册后我将它们转发到新活动,以便选择我需要唯一的用户名。我的想法是搜索整个数据库,以查看该用户名是否已经存在。这是我试图做到这一点,但直到现在没有运气:
submitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("UserName", "Click: ");
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("USERS");
mDatabase.orderByChild("username").equalTo("name1").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
//Here you can get all data
Log.d("UserName", "onDataChange: "+snapshot.toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
我也试过这个:
submitBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("UserName", "Click: ");
DatabaseReference mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
Query query = mFirebaseDatabaseReference.child("USERS").orderByChild("username").equalTo("name1");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//TODO get the data here
Log.d("UserName", "onDataChange: " + dataSnapshot.toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
query.addValueEventListener(valueEventListener);
}
});
答案 0 :(得分:1)
您的代码无法正常工作的唯一原因是"用户名"不是USERS表的直接子项。 您的直接孩子将有随机ID,您可以使用ChildEventListener迭代,如下所示:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("USERS");
mDatabase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
User user = dataSnapshot.getValue(User.class); // pojo
if(user.getUsername().equals("name1") {
// do something
}
}
...
)