Reputation: 53
My Database Structure is:
{
"Users" : {
"KTTbTIq2A4aZcjKPSYlZhrBiDwD3" : {
"Email" : "[email protected]",
"ID" : "KTTbTIq2A4aZcjKPSYlZhrBiDwD3",
"UserName" : "GokulNew2"
},
"ovxZPZeyy2VlZUP1K0vv9VtiThu1" : {
"Email" : "[email protected]",
"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,
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();
}
});
Upvotes: 0
Views: 127
Reputation: 138824
To get the key of the node (ovxZPZeyy2VlZUP1K0vv9VtiThu1) if the "UserName" matches to "GokulNew1", please use the following lines of code:
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:
ovxZPZeyy2VlZUP1K0vv9VtiThu1
Upvotes: 1
Reputation: 264
You need to add query with this in order to match this to particular string. It'll return only that item, otherwise simple fetch will have list.
Query query = reference.orderByChild("UserName").equalTo("GokulNew1");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot){
//Check for id here.
}
Don't forget to add query to the firebase rules.
Upvotes: 1