I am trying to pick a contact using intent in android. The information I need is name, phone no and email address of contact. following what I have tried so far.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
}
}
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String phoneNo = cursor.getString(phoneIndex);
String name = cursor.getString(nameIndex);
String contactBookId = uri.getLastPathSegment();
String email = null;
try {
Cursor emailCur
= getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactBookId}, null);
emailCur.moveToFirst();
while (emailCur.moveToNext()) {
String phone = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCur.getInt(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email.getTypeLabel(getActivity().getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
}
emailCur.close();
} catch (Exception e) {
Log.e(TAG, "Exception while trying to fetch email addresses of " + name + ":" + e.getMessage());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
here is how I am firing intent
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
My problem is that emailCur never reads any email address. Code never enters in loop.
Edit
even If I ditch getLastPathSegment()
and retrieve id as follows I get same behaviour
int idIndex = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
String contactBookId = cursor.getString(idIndex);