0

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

Rahul R
  • 303
  • 2
  • 11

1 Answers1

1

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • thank you for your response , i tried the above code sorry to say that it doesn't worked – Rahul R Jan 15 '23 at 15:12
  • "doesn't worked" is really hard to help with. Is there an error message? If not: If you set a breakpoint on each line of the code you shared, run the code in a debugger, and then check the value of each variable on each line, which is the **first** line that doesn't do what you expect it to do? – Frank van Puffelen Jan 15 '23 at 15:49
  • problem resolved thanks a lot for your effort – Rahul R Jan 20 '23 at 07:25