0

I am trying to make a list of contacts that have email, phone or both. For this purpose I am using ContentResolver with URI set to ContactsContract.Data.CONTENT_URI and I select by these conditions:

String SELECTION = ContactsContract.Data.DISPLAY_NAME_PRIMARY + "<>'' AND " + ContactsContract.Data.IN_VISIBLE_GROUP + "=1" + " AND (" + ContactsContract.Data.MIMETYPE + "=? OR " + ContactsContract.Data.MIMETYPE + "=?)";
String[] SELECTION_ARGS = new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
                ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};

I am interested only in Name of such contact. But because Data table holds each information for given contact at separate row, the resulted cursor has duplicate entries in it.

Is there any way how to DISTINCT those entries? I am using CursorLoaderManager with CursorAdapter (maybe only way is to filter them out when loader finishes?).

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
bakua
  • 13,704
  • 7
  • 43
  • 62
  • Have you seen [this](http://stackoverflow.com/questions/2315203/android-distinct-and-groupby-in-contentresolver), it's a bit old but might be helpful. – ci_ May 14 '15 at 12:43
  • I've tried it all but unfortunately nothing helps due to those "hacks" were fixed in latest android versions or they don't work with contact content providers :/ – bakua May 14 '15 at 13:07

1 Answers1

0

Use following code.

ContentResolver cr = context.getContentResolver();
    String[] PROJECTION = new String[] { ContactsContract.RawContacts._ID, 
            ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Email.DATA, 
            ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
    String order = "CASE WHEN " 
            + ContactsContract.CommonDataKinds.Phone.NUMBER
            + " NOT LIKE '%@%' THEN 1 ELSE 2 END, " 
            + ContactsContract.Contacts.NUMBER
            + ", " 
            + ContactsContract.CommonDataKinds.Email.DATA
            + " COLLATE NOCASE";
    String filter = ContactsContract.CommonDataKinds.Email.DATA + " NOT LIKE ''";
    Cursor cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, filter, null, order);
Jitesh Dalsaniya
  • 1,917
  • 3
  • 20
  • 36
  • ContactsContract.Contacts.NUMBER doesn't exists. Do you mean ContactsContract.CommonDataKinds.Phone.NUMBER? – bakua May 14 '15 at 13:01
  • But still, this will not exclude duplicate entries from select result. – bakua May 14 '15 at 13:26