I'm writing a ContactPickerDialog for a custom Preference.
Depending on the preference the ContactPickerDialog should show all contacts with at least one phone number or all contacts with at least one eMail-address. No contact should be shown twice, no matter how many phone-numbers or eMail-addresses are connected with this contact.
I have no problem with getting all contacts with at least one phone-number as I can use HAS_PHONE_NUMBER
in the where-clause. But I have no idea how to get the contacts with at least one eMail-address without getting some contacts multiple times if they have more than one eMail-address.
This is my code:
public void LoadContactsWithTarget(Context context, PickContactDialog.PickTarget pickTarget)
{
try
{
String[] projection = new String[]
{
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
ContactsContract.Contacts.PHOTO_URI,
ContactsContract.Contacts._ID
};
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " ASC";
Uri uri = null;
String where = "";
if (pickTarget == PickTarget.PHONE_NR)
{
// works great, I only get one contact, no matter how many phone-numbers are connected with this contact
uri = ContactsContract.Contacts.CONTENT_URI;
where = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = 1";
}
else if (pickTarget == PickTarget.EMAIL)
{
// I get one contact/entry for each eMail-address that is connected with the contact but I only want to get one contact, no matter how many eMail-addresse are connected with the contact
uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
where = ContactsContract.CommonDataKinds.Email.DATA + " NOT LIKE ''";
}
Cursor cursor = context.getContentResolver().query(uri, projection, where, null, sortOrder);
if (cursor.moveToFirst())
{
int iNameColumn = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
int iThumbnailColumn = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI);
int iImageColumn = cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_URI);
int iIDColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
while (!cursor.isAfterLast())
{
Contact contact = new Contact(cursor.getInt(iIDColumn),
cursor.getString(iNameColumn),
cursor.getString(iThumbnailColumn),
cursor.getString(iImageColumn));
_lstContacts.add(contact);
cursor.moveToNext();
}
}
cursor.close();
}
catch(Exception e) { }
}
Any help is really appreciated