Firebase Database Query for finding popular items

I’m working with Firebase again today. I want to query if an item is popular and if so show it in a tab I’ve called “Popular” within my app.

{
    "PROMOTED" : true,
    "downvote" : 2,
    "image" : "my image location",
    "station" : "my station name",
    "tag" : "station tagline",
    "upvote" : 10000,
    "url" : "url to station"
}

this is an individual item from my Firebase tree. I want to use the child “upvote” to deem if the item is popular. how can I only show items that have an upvote of let’s say more than 1000?

This is the code I have so far within my app

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

Query query = ref.orderByChild("upvote");

query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        Stations_Firebase station_items = new Stations_Firebase();
        station_items.clearArrays();

        for (DataSnapshot snap : snapshot.getChildren()) {

            station_items = snap.getValue(Stations_Firebase.class);
            String a = station_items.getStation();
            String b = station_items.getTag();
            String c = station_items.getUrl();
            Long d = station_items.getUpvote();
            Long e = station_items.getDownvote();
            String f = station_items.getImage();

            station_items.setArrays(a, b, c, d, e, f);
            station_items.ConvertArrays();
            station_items.SetAdapter(getContext(), mlist);
        }
    }
});

Answer

How can I only show items that have an upvote or let’s say more than 1000?

To get the items that have at least one up-vote, please use the following query:

Query query = ref.orderByChild("upvote").startAt(1);

If you want to get the items that have at least 1000 up-votes, please use the following query:

Query query = ref.orderByChild("upvote").startAt(1000);

From the docs:

  • startAt()

Return items greater than or equal to the specified key or value depending on the order-by method chosen.

Leave a Reply

Your email address will not be published. Required fields are marked *