M adnan
M adnan

Reputation: 98

Data duplicate in listview while fetching from firebase android studio

when I fetch data from firebase in listview data repeat itself how to stop duplication anybody help me, please...

databaseReference.child("Conversation")
    .child(current_token)
    .child(user_token)
    .addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        String msgs = null;
        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
          ChatMessage chatmessages = snapshot.getValue(ChatMessage.class);
          msgs = chatmessages.getMessageText();
          Log.e("chk", "" + msgs);
          arrayList.add(new chatmessages(msgs)); //here is duplication
        }

        chat = new Chat(getApplicationContext(), arrayList);
        chatlistView.setAdapter(chat);
      }

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

      }
    });
}

Upvotes: 0

Views: 1207

Answers (3)

marina
marina

Reputation: 1680

You have created arrayList in the class instead of onDataChange method.

Therefore the list of data is growing with duplicate data. You could make following

1) Declare arrayList in onDataChange

2) call arrayList.clear() before foreach. In this case you should instead

chat = new Chat(getApplicationContext(), arrayList);
chatlistView.setAdapter(chat);

call

chatlistView.notifyDatasetChanged();

and initialize it previously

Upvotes: 1

Kalpesh Kulye
Kalpesh Kulye

Reputation: 149

clear arraylist before adding new list from firebase or initialise list again i.e.

arraylist = new ArrayList();

Upvotes: 2

leimenghao
leimenghao

Reputation: 226

Override hashCode() and equals() methods in chatmessages class so every chatmessages is unique.

Upvotes: 0

Related Questions