user3528466
user3528466

Reputation: 196

how to filter firebase object using field inside list

I am an android developer, but this is not really important. I accept solution also in other programming language.

I have a collection of "answers" under /root/answers. Here the data is stored using push method, so each child has a unique id. Each child has a field called "user_ref" which is a simple string. I need to populate my list with all answers where a given string match with "user_ref". So I built my DatabaseReference with:

DatabaseReference r = FirebaseDatabase.getInstance().getReference(ANSWERS_REF)
            .startAt("id_123")
            .endAt("id_123")
            .getRef();

It works but every time this Database references return all answers and not only selected

Upvotes: 1

Views: 1085

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598648

The problem is caused by calling getRef() at the end of your statement. That returns the DatabaseReference of the location that you query, so that is all answers.

DatabaseReference allAnswers = FirebaseDatabase.getInstance().getReference(ANSWERS_REF);
Query r = allAnswers.startAt("id_123")
                    .endAt("id_123");

Since Query is the base class of DatabaseReference, you can also attach listeners to the Query.

r.addChildEventListener(new ChildEventListener() { ...

Upvotes: 1

Omar El Halabi
Omar El Halabi

Reputation: 2128

Try to use equalTo("id_123") instead of startAt() and endAt() (I am assuming that id_123 is a value for user_ref). Namely as follows,

DatabaseReference r = FirebaseDatabase.getInstance().getReference(ANSWERS_REF)
            .orderByChild("user_ref")
            .equalTo("id_123")
            .getRef();

Hope it helps!

Upvotes: 2

Related Questions