1

Firebase Structure

How to show the contents in RecyclerView in Android app based on the number of likes in the post? I know how to sort the posts in ascending and descending order but I am having a problem in sorting them based on the number of likes in the post.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Pots
  • 41
  • 3

1 Answers1

0

I know how to sort the posts in ascending and descending order

Then it will be very simple to order according to the number of likes. To solve this, you should add a new property to your post object named numberOfLikes and increment its value every time you get a new like. To get the number of likes, attach a listener on the postId reference and use getChildrenCount() method on your DataSnapshot object like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postIdRef = rootRef.child("Likes").child(postId);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        long numberOfLikes = dataSnapshot.getChildrenCount();
        Log.d("TAG", String.valueOf(numberOfLikes));
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
postIdRef.addListenerForSingleValueEvent(valueEventListener);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • sir, thank you for your answer but sir after counting the likes of each post how to display the posts based on more number of likes post at first and least number of likes post at last in recycler view. – Pots Jul 30 '18 at 15:37
  • You said "I know how to sort the posts in ascending and descending order", what have you tried so far? Have you tried to use `orderByChild("numberOfLikes")`? – Alex Mamo Jul 30 '18 at 15:44
  • Sorry sir, I know how to display the contents in reverse order not ascending and descending. By ascending and descending i meant front and reverse order of data from database. – Pots Jul 30 '18 at 17:27
  • Take a look at [this](https://stackoverflow.com/questions/46777129/how-can-i-print-data-in-reverse-order-using-firebase-in-android). – Alex Mamo Jul 30 '18 at 17:40
  • Is there everything alright, have you solved the issue? – Alex Mamo Jul 31 '18 at 09:14