Home > database >  Firebase search by child value KOTLIN
Firebase search by child value KOTLIN

Time:01-16

This is my firebase realtime database structure enter image description here

I want to retrieve all questions with QID = "PQ1" . What i tried is given below . Its result is null .

database.child("Question").child("QID").equalTo("PQ1").limitToFirst(200).get().addOnSuccessListener {
Log.i("12345", "Got value ${it.value}")
}

My references :

Firebase - Search a child by value

Firebase search by child value

Search firebase by Child of child value

CodePudding user response:

Your call to database.child("Question").child("QID") looks for a child node at path /Question/QID in your database, which doesn't exist and thus explains why you get an empty snapshot.


To query the Firebase Realtime Database needs two steps:

  1. You order all child nodes on a property, on their key, or on their value by calling on of the orderBy... methods.
  2. You then filter the ordered child nodes by calling one or more of the equalTo, startAt, startAfter, endAt, endBefore, limitToFirst and/or limitToLast methods.

While you're doing #2, you're not ordering the nodes first by calling orderBy....

The correct code:

database.child("Question").orderByChild("QID").equalTo("PQ1").limitToFirst(200).get().addOnSuccessListener {
    Log.i("12345", "Got value ${it.value}")
}

Also don't forget that executing a query will potentially have multiple results, so the snapshot in it.value contains a list of those results and you will need to iterate over its children. Even if there is only a single result, the snapshot will contain a list of one result.

  • Related