My Database Structure is:
JavaScript
x
{
"Users" : {
"KTTbTIq2A4aZcjKPSYlZhrBiDwD3" : {
"Email" : "g2@g.com",
"ID" : "KTTbTIq2A4aZcjKPSYlZhrBiDwD3",
"UserName" : "GokulNew2"
},
"ovxZPZeyy2VlZUP1K0vv9VtiThu1" : {
"Email" : "g1@g.com",
"ID" : "ovxZPZeyy2VlZUP1K0vv9VtiThu1",
"UserName" : "GokulNew1"
}
}
}
In this structure, I need to get “ID” (which is autogenerated) as “ovxZPZeyy2VlZUP1K0vv9VtiThu1” if the “UserName” matches to “GokulNew1”. And I need to store the ID in String ID.
And My Code is,
JavaScript
private DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
String Id;
String Name = "GokulNew1";
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
recyclerId= snapshot.child("ID").toString();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
Advertisement
Answer
To get the key of the node (ovxZPZeyy2VlZUP1K0vv9VtiThu1) if the “UserName” matches to “GokulNew1”, please use the following lines of code:
JavaScript
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
Query queryByUserName = usersRef.orderByChild("UserName").equalTo("GokulNew1");
queryByUserName.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot uidSnapshot : task.getResult().getChildren()) {
String uid = uidSnapshot.getKey();
Log.d("TAG", uid); //Do what you need to do with the uid
}
} else {
Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
JavaScript
ovxZPZeyy2VlZUP1K0vv9VtiThu1