Skip to content
Advertisement

My RecyclerView duplicates my items views

So I’m testing the Recycler View and facing some troubles when adding new item.

I have a RecyclerView where I try to display a user’s contacts, but when I create a new elemen, all the contacts duplicate. I know that I should clean my view before adding new data, but I’m not sure how to do that.

Here’s my main activity code

for (DataSnapshot postSnapshot : snapshot.child(currentUser.getUid()).getChildren()) {
                    Document document = postSnapshot.getValue(Document.class);
                    mDocuments.add(document);
                }
adapter = new ContactAdapter(getApplicationContext(), mContacts, mAuth);
recyclerView.setAdapter(adapter);

Here’s adaptor

@Override
public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
    Contact contactCurrent = mContacts.get(position);

    holder.contactName.setText("Name: " + contactCurrent.getName());
    holder.contactPhone.setText("Phone number: " + contactCurrent.getPhone());
}

public static class ContactViewHolder extends RecyclerView.ViewHolder {

    public TextView contactName, contactPhone;
    public ImageButton deleteContact;

    public ContactViewHolder(@NonNull View itemView) {
        super(itemView);

        contactName = itemView.findViewById(R.id.contact_name);
        contactPhone = itemView.findViewById(R.id.contact_phone);
        deleteContact = itemView.findViewById(R.id.delete_contact);
    }
}

Advertisement

Answer

Ohk, just use mDocuments.clear(); before adding data to mDocuments. See below code.

for (DataSnapshot postSnapshot : snapshot.child(currentUser.getUid()).getChildren()) {
                    mDocuments.clear();
                    Document document = postSnapshot.getValue(Document.class);
                    mDocuments.add(document);
                }
adapter = new ContactAdapter(getApplicationContext(), mContacts, mAuth);
recyclerView.setAdapter(adapter);

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement