Sajeeb Shahriar
Sajeeb Shahriar

Reputation: 112

How can I get the username by search using the phone number in firebase realtime databse?

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
  }
}

I want to search by this phone number to get the username

Upvotes: 0

Views: 86

Answers (2)

Dharmaraj
Dharmaraj

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

Alex Mamo
Alex Mamo

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

Related Questions