3

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?

Community
  • 1
  • 1
Elohim
  • 41
  • 2

2 Answers2

1

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

whitebrow
  • 2,015
  • 21
  • 24
0

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
Want2bExpert
  • 527
  • 4
  • 11