1

Is it possible to order my ListView of posts based on the likes (the most liked post must be displayed above)?

How my Firebase database looks like

I already know how I can order it based on timestamp. But as you can see the likes is a collection in Posts.

Timestamp code:

Query firstQuery = firebaseFirestore.collection("Posts").orderBy("timestamp", Query.Direction.DESCENDING).limit(3);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Sge
  • 21
  • 6

1 Answers1

2

If you already know how to order based on timestamp, then you should do in the same way to order by likes. So to solve this, you need to add a new property under each post named likes and use the following line of code to query:

Query firstQuery = firebaseFirestore.collection("Posts").orderBy("likes", Query.Direction.DESCENDING).limit(3);

To update a the likes property, I recomment you using Firestore Transactions.

You can count the number of documents within a collection but in your case, the best option is to add a new property, as explained above.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Yes, it could. You can add a listener to get the number of likes and write it under the corresponding post. But il will be harder to maintain. In my solution, there a single property that will be updated and that's it. It's up to you which solution you choose. – Alex Mamo Jun 06 '18 at 14:04
  • Do you think that my answer helped you? – Alex Mamo Jun 06 '18 at 14:04
  • Thank you for your helpful answers. I understand and want to use the transactions method but I don't really know the right way to implement it in my file. Can you help me with that? – Sge Jun 06 '18 at 14:19
  • 1
    Yes, sure. First, I recommend checking out the documentation and trying it. If you get stuck during a specific step, show what you've tried and in order to follow the rules of this comunity, please post another fresh question, so me and other users can help you. – Alex Mamo Jun 06 '18 at 14:33
  • Also see the Firestore documentation page on maintaining counters: https://firebase.google.com/docs/firestore/solutions/counters – Frank van Puffelen Jun 06 '18 at 14:46
  • @FrankvanPuffelen Thanks Frank! – Alex Mamo Jun 06 '18 at 14:47