1

I have Firebase node that look like this

Firebase node

How can i make a condition if (name.equalsTo("someValue") to scan database inside campus and get reference to node with key? I this case, i want to get reference or key of kazjap

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
IBlackVikingl
  • 643
  • 2
  • 7
  • 20

1 Answers1

2

To find the node under /campus/building where name has a certain value, you can use a query like this:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("campus/building");
Query query = ref.orderByChild("name").equalTo("someValue");

And then read the results of the query with:

query.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 {
            for (DataSnapshot childSnapshot: task.getResult().getChildren()) {
                Log.d("firebase", String.valueOf(childSnapshot.getKey()));
            }
        }
    }
});

Or:

query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            // Handle the data
            Log.d("TAG", childSnapshot.getKey())
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting User failed, log a message
        Log.w("firebase", "Error getting data", databaseError.toException());
        // ...
    }
});

Firebase queries only work on direct child nodes, so this only works if you know the /campus/building part of the path already. There is no way to search across the entire campus for a building by its name in any campus. For more on that, see Firebase Query Double Nested

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Did you already try the code in my answer? The `child.getKey()` in the code in my answer gets the key of the matching child nodes. Here I log it, but you can do with it whatever you need. – Frank van Puffelen Jun 12 '21 at 04:14
  • Is mDatabase is DatabaseReference or Query? Upper code doesn't seem to match bottom code. – IBlackVikingl Jun 12 '21 at 04:18
  • 1
    @IBlackVikingl try running the query as in updated answer. The `userSnapshot` should be the child node matching your query. – Dharmaraj Jun 12 '21 at 04:34