Elohim
Elohim

Reputation: 41

How do I delete contacts repeated in the listview?

Following the tutorial get android contact phone number list

I pulled the phone numbers and names of contacts, how do I get a listview clean, no duplicate contacts and possibly sorted by name?

Upvotes: 3

Views: 427

Answers (2)

Want2bExpert
Want2bExpert

Reputation: 527

Try this;

  • Use a Data Structure that doesn't allow duplicate e.g. HashMap
  • Use the phone number as the Key
    • e.g. Key = phoneNumber, Value = Name OR
    • Key = phoneNumber, Value = List of OtherContactDetails
  • Use Collections to sort
  • Pass the sorted Collections to Your Adapter

Upvotes: 0

whitebrow
whitebrow

Reputation: 2005

Try this:

Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
List<String> phoneNumbers = new ArrayList<String>();
while (phones.moveToNext()) {
    String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    System.out.println(".................."+phoneNumber); 

    if(!phoneNumbers.contains(phoneNumber)) {
        phoneNumbers.add(phoneNumber);
    }
}
Collections.sort(phoneNumbers);

In short: check if the phone number is not already in the list before adding it. It might be handy to remove any whitespace from each phone number before making the check so that you're sure no duplicates make it through.

Some more info about sorting: http://developer.android.com/reference/java/util/Collections.html#sort%28java.util.List%3CT%3E%29

Upvotes: 1

Related Questions