User picks a contact from their contacts and this is the callback function (I'm skipping onActivityResult(...)
code, it's working fine):
private User addUserFromContactData(Intent data) {
Uri contactData = data.getData();
// Cursor loader to query contact information
CursorLoader cl = new CursorLoader(this);
String[] projection = { ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA };
cl.setProjection(projection);
cl.setUri(ContactsContract.CommonDataKinds.Email.CONTENT_URI);
cl.setSelection(ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?");
cl.setSelectionArgs(new String[] { contactData.getLastPathSegment() });
// Execute query and get results from cursor
Cursor c = cl.loadInBackground();
final int nameIndex = c.getColumnIndex(projection[0]);
final int emailIndex = c.getColumnIndex(projection[1]);
User user = null;
if (c.moveToFirst()) {
user = new User();
user.setName(c.getString(nameIndex));
user.setEmail(c.getString(emailIndex));
}
c.close();
return user;
}
This method is working fine with contacts that have an email address. But when I select a contact without it, no results are found. Email is optional for me, so if there is no email, I will only use the contact name. Seems like I'm only selecting contacts with email address.
Can anyone help me? Maybe I need to query twice, first time to get name and second to get optional email?
Thanks guys.