5

I am using the following to fetch a username from Firebase. But in this case, how do I get to know, if the username exists or not.

Firebase firebaseRef = new Firebase("<Firebasae_URL>/Users");
Query query=firebaseRef.orderByChild("username").equalTo("username");
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
Arun George
  • 1,167
  • 3
  • 15
  • 29
  • This question already has an answer here. http://stackoverflow.com/a/36256978/3145960 See the `dataSnapshot.exists()`. – Reaz Murshed Apr 24 '16 at 17:23
  • How do I handle it, when I use addChildEventListener. – Arun George Apr 24 '16 at 17:47
  • See the answer posted – Reaz Murshed Apr 24 '16 at 17:52
  • 1
    Using a `ChildEventListener` in this case won't be possible. The methods of that listener will get called **when** a child is added/deleted/moved/changed, while you are look to see **if** a specific child exists. You'll need a `ValueEventListener` as @ReazMurshed says is the way to detect client-side if a specific element exists. – Frank van Puffelen Apr 24 '16 at 18:15
  • 1
    Note that a pure client-side solution has inherent race conditions. See this [answer from Kato for a complete solution](http://stackoverflow.com/questions/25294478/how-do-you-prevent-duplicate-user-properties-in-firebase). You'll have to translate the JavaScript to Java, but given that the Firebase SDKs have the exact same structure between these technologies, that should not be too difficult. – Frank van Puffelen Apr 24 '16 at 18:18

2 Answers2

5

So in your case the code should be like this, to find an username exists in your database.

Firebase firebaseRef = new Firebase("<Firebasae_URL>/Users").child("username");
firebaseRef.addListenerForSingleValueEvent(new ValueEventListener) {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            // User Exists
        }
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }
});
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
0

The solution I found to check if a query return value was

let docRef = db.collection('videos').select('id').where('id','==',quoteData.id);
docRef.get().then(function(doc){              
    if(doc.size > 0){
        // return value
    }
    else{
        // no return value
    }
})
jomarmen
  • 97
  • 1
  • 2
  • 8