Reputation: 112
I want to search by the phone number and get the parent key "Sajeeb" or the username using Java. Currently, I am taking the phone number as input and getting all keys and values of the "user" child.
Security rules:
{
"rules": {
".read": true,
".write": true
}
}
Upvotes: 0
Views: 86
Reputation: 50910
You can use orderByChild
with equalTo
to get that user's node only:
String myUserId = getUid();
Query myUserQuery = databaseReference.child("users").orderByChild("phone").equalTo(PHONE_NUMBER);
myUserQuery.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
Log.d("firebase", String.valueOf(task.getResult().getValue()));
}
}
});
Try setting the rules to:
{
"rules": {
"users": {
".read": true,
".write": true,
".indexOn": ["phone"]
}
}
}
Do note that your current rules allow anyone to read/write to database so you might want to rewrite those. For this issue, you just need to add indexOn
as shown above.
Upvotes: 2
Reputation: 138969
Since "Sajeeb" is the key of the node, you can simply get it using a call to ".getKey()". So please try the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
Query queryByPhone = usersRef.orderByChild("phone").equalTo("+8801413565895");
queryByPhone.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String userName = ds.getKey();
Log.d("TAG", userName);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
Alternatively, you can use:
String userName = ds.child("userName").getValue(String.class);
To get the value of the "userName" field. Both solutions will work and will produce the following output in the logcat:
Sajeeb
Upvotes: 1