0

My Database Structure is:

{
"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,

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();
        }
    });
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Gokul
  • 53
  • 6
  • 2
    I really don't understand how the accepted answer will work? Can you please provide some details? The provided code is really incomplete. How does "Check for id here" work? Furthermore, what's the point of using the addListenerForSingleValueEvent? This approach, nowadays it is considered to be old in favor of the new recently added **get()** method? What does "Don't forget to add query to the firebase rules" mean? In my opinion, that answer might only confuse future visitors. It simply doesn't make any sense at all! – Alex Mamo May 14 '21 at 09:54

2 Answers2

1

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
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hi Alex am getting the error as Index not defined, add ".indexOn": "UserName", for path "/Users", to the rules And this error is not permenant after few seconds it's working fine. – Gokul May 14 '21 at 09:17
  • Have you tried to create the index, that is said it's complaining? – Alex Mamo May 14 '21 at 09:31
  • where to add it Alex? – Gokul May 14 '21 at 11:08
  • In the Security Rules. You might check [this](https://stackoverflow.com/questions/43260689/adding-and-indexon-value-into-firebase-rules) out. – Alex Mamo May 14 '21 at 11:10
  • But I still don't understand how that accepted answer worked. Can you please provide some details? – Alex Mamo May 14 '21 at 11:20
  • In //check for id i have placed this String uid = uidSnapshot.getKey(); and a Toast message for my reference. And its working fine. – Gokul May 14 '21 at 12:06
  • Good to hear that. So if you could Toast the `uid`, this means that you solved the problem, right? – Alex Mamo May 14 '21 at 12:15
  • Not like that. For checking purpose only i used Toast, that's all – Gokul May 14 '21 at 12:18
1

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.

Chanpreet Singh
  • 204
  • 1
  • 5