Home > Enterprise >  How to retrieve details of users who commented in a group chat
How to retrieve details of users who commented in a group chat

Time:09-25

I am trying to retrieve details of users who commented in a group but the user detail keeps multiplying after each comment. The app is similar to whatsapp which shows each participant in a group, but the only difference is that everyone can access the group, and once you comment in the group, you are added as a participant. My issue is that for every comment, the user details keep adding. I want to retrieve the user once for all comments.

My code:

DatabaseReference databaseReference3 = FirebaseDatabase.getInstance().getReference("Groups");

databaseReference3.child(groupId).child("Messages").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {

        participantArrays.clear();

        for (DataSnapshot dataSnapshot: snapshot.getChildren()){
            ParticipantArray array = dataSnapshot.getValue(ParticipantArray.class);
            if(array.getSender() != null) {
                participantArrays.add(array);
            }
        }
        adapter = new ParticipantsAdapter(participantArrays, GroupEdit.this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        recyclerView.setHasFixedSize(true);
    }


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

    }
});
public class ParticipantArray {

    String sender;
    String msg;

    public ParticipantArray(String sender, String msg) {
        this.sender = sender;
        this.msg = msg;
    }


    public ParticipantArray(){}

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }
}

Adapter:

The image shows duplication after each comment

CodePudding user response:

You'll want to check if the sender is already in the array before adding it again. Something like this should do the trick:

Set<String> senders = new HashSet<>();
for (DataSnapshot dataSnapshot: snapshot.getChildren()){
    ParticipantArray array = dataSnapshot.getValue(ParticipantArray.class);
    if(array.getSender() != null && !senders.contains(array.getSender())) {
        participantArrays.add(array);
        senders.add(array.getSender());
    }
}

Unrelated to that, there is no need to create an entire new adapter each time the data changes. Instead, you can create the adapter only once (outside of the listener), update the participantArrays when the data changes, and call adapter.notifyDataSetChanged() to tell it to refresh its view.

  • Related