Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Remove Duplicate Contacts

I am trying to display contacts in Recycler View everything is working fine but contacts are getting displayed twice or thrice.

Here is the Code

 RecyclerView recyclerView;
 List<Contacts> contactsList;
 ContactsAdapter adapter;

 public void getContactList() {
    Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null, null, null,
            "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ") ASC");
    while (cursor.moveToNext()) {
        String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        Contacts contacts = new Contacts(name, number);
        if (contactsList.contains(contacts)){
            cursor.moveToNext();
        }
        else {
            contactsList.add(contacts);
        }
        adapter = new ContactsAdapter(contactsList, getApplicationContext());
        recyclerView.setAdapter(adapter);

        adapter.notifyDataSetChanged();
    }
}

So, how can I solve this problem?

like image 318
HARSH ASHRA Avatar asked Sep 27 '26 08:09

HARSH ASHRA


1 Answers

Pass only phoneNumber as a key and phoneName as a value You can use :

Map<String, String> map = new HashMap<>();
map.put("A", "1");
...
System.out.printf("Before: %s%n", map);

// Set in which we keep the existing values
Set<String> existing = new HashSet<>();
map = map.entrySet()
    .stream()
    .filter(entry -> existing.add(entry.getValue()))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.printf("After: %s%n", map);  

for example :

Before: {A=1, B=2, C=2, D=3, E=3} After: {A=1, B=2, D=3}
like image 159
NizarETH Avatar answered Sep 29 '26 22:09

NizarETH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!