Showing only certain items from a Firebase database node

0

Issue

I have a database node called Stations and inside there will be various items associated with that station. eg the name/title description. Some of these children will contain a Boolean called PROMOTED if this Boolean equals true.

I want it to appear in my promoted tab with in my app. How can I make sure only these children appear in there? At the moment my fragment is just listing all stations. An example appears below.

Would it be something to do with the query?

ref = db.getReference().child(DATABASE_CHILD);

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot snap : snapshot.getChildren()) {
                String Title = snap.child("TITLE").getValue(String.class);
                String Desc = snap.child("DESCRIPTION").getValue(String.class);
                String  Thumbup = snap.child("THUMBUP").getValue(String.class);
                String Thumbdown = snap.child("THUMBDOWN").getValue(String.class);
                String Image = snap.child("IMAGE").getValue(String.class);
                setTextViews(Title,Desc,Thumbup,Thumbdown,Image);
            }
        }

Solution

Selecting some nodes based on their value requires the use of a query, which is how you order and filter data in Firebase.

In this case it sounds like you want to order on the child property PROMOTED and then filter for true values, which would look like this:

Query query = ref.orderByChild("PROMOTED").equalTo(true);

query.addValueEventListener(new ValueEventListener() {
    ...

The rest of your code can stay unmodified.

Answered By – Frank van Puffelen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More