0

I want to create a small social app. I'm almost done with it, but I don't know how to show comment items in a RecyclerView, based on those which are most-liked.

Here is the code

 //This is commentAdapter
 public void onBindViewHolder(@NonNull final Myholder myHolder, final int i) {
    final ModelComments modelComments = commentsList.get(i);
    String cLikes = commentsList.get(i).getcLikes(); //this is for like

myHolder.user_comment.setText(modelComments.getComment());
    myHolder.clickBtn.setText(cLikes);//to show how many likes the user get



//This is commentsActivity
 RecyclerView recyclerView;
FirebaseAuth firebaseAuth;
FirebaseUser user;
private CommentAdapter commentAdapter;
private List<ModelComments> commentsList;

recyclerView = findViewById(R.id.comment_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    //show newest comment first and then old
    layoutManager.setStackFromEnd(true);
    layoutManager.setReverseLayout(true);
    recyclerView.setLayoutManager(layoutManager);
    commentsList = new ArrayList<>();
    commentAdapter= new CommentAdapter(this, commentsList);
    recyclerView.setAdapter(commentAdapter);

showAllComment();
}

private void showAllComment() {
 try {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("comments");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                commentsList.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    ModelComments modelComments = snapshot.getValue(ModelComments.class);
                    commentsList.add(modelComments);
                }

                commentAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Again, is there any way to make this possible? If you don't understand, comment on this question.

Md. Sabbir Ahmed
  • 850
  • 8
  • 22
Coder
  • 53
  • 1
  • 7

1 Answers1

0

As we can see, you already did the binding by doing the following

commentsList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
    ModelComments modelComments = snapshot.getValue(ModelComments.class);
    commentsList.add(modelComments);
}
commentAdapter.notifyDataSetChanged();

First, you cleared the list, then added the comments, and lastly calling the notifyDataSetChanged. What you've missed is to sort the list before notifying data changed

Please check this link on how to sort list. Sort ArrayList of custom Objects by property

Jaype Sison
  • 61
  • 1
  • 1