1

I know that there are many similar questions but no one has the answer I am looking for, all the questions I consulted have answers talking about childrenEvetListeners...

My question is so much simpler. This my Firebase database: enter image description here

My question is: how can I make a query, checking if a user with the username="fofof" exists?

Cœur
  • 37,241
  • 25
  • 195
  • 267
rainman
  • 2,551
  • 6
  • 29
  • 43

1 Answers1

1

You have a hybrid structure, which complicates things. But if you are just looking for a match under /users/-K...., you can find the match with something like:

Query query = ref.child("users").orderByChild("User/username").equalTo("fofof");
query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
            Log.i(TAG, "fofof exists and is stored under key "+userSnapshot.getKey());
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
    }
});

A few warnings about your current set-up though:

  • you're storing users under a push ID. While push IDs are great for collections that don't have a natural key and that you want to store chronologically, it is better to store your users under the UID. So e.g. /users/s5iu....
  • you've nested the user information one level deeper than is necessary. While this works, I'd get rid of the User level in your tree.
  • you have a user directly under /users, while others are stored one level deeper. Creating such a hybrid model is a bad idea.
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you very much Frank, as you know the push ID is inserted because i am using the push() function to create new nodes, i tried to avoid using push(), but in that case everytime a insert new user it overwrites the existing node and no new node is created, is there any way to create new nodes ( in my case for users) without using push() ?? – rainman Sep 18 '16 at 02:15
  • `ref.child("users").child(userId).setValue(...)` – Frank van Puffelen Sep 18 '16 at 02:22