My problem is that I want to get a User or just a User UID via email or name. Tried to write the query, but I'm getting all users and then iterating through them and then getting the user but I think it's an expensive task. That's why I'm asking which is the best way to get only one User/Uid from Realtime Database.
This is what I came up with (But don't think is the best way):
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot child : snapshot.getChildren()) {
if (child.getValue(User.class).getEmail().equals(client.getEmail())){
User user = child.getValue(User.class);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
CodePudding user response:
According to your last comment:
I have the corresponding details of each user (email, name), and I want to get the UID of one user (no matter which one)
To get a particular user from the database based on a particular email address, the query that you are already using:
Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
Returns only the users who have the field email
set to what client.getEmail()
returns. For instance, if client.getEmail()
returns [email protected] then you'll get a single result, according to your screenshot, which is the first one. That being said, the following if statement, doesn't make sense to be used:
if (child.getValue(User.class).getEmail().equals(client.getEmail())){
User user = child.getValue(User.class);
}
Since the key of the user node is represented by the UID, then you should get it like this:
Query emailQuery = usersRef.orderByChild("email").equalTo(client.getEmail());
emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot child : snapshot.getChildren()) {
User user = child.getValue(User.class);
String uid = child.getKey();
//Do what you need to do with UID.
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d("TAG", error.getMessage()); //Never ignore potential errors!
}
});
That's the simplest, cheapest way to query the Realtime Database, in which you return only the elements that you are interested in and that satisfy a particular condition.