I'm using ACTION_PICK intent for contacts and I want to extract the name and phone from the picked contact.
private static final int CONTANTS_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_urgent_contacts);
Intent contact_picker = new Intent(Intent.ACTION_PICK);
contact_picker.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(contact_picker, CONTANTS_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CONTANTS_REQUEST_CODE && resultCode == RESULT_OK){
onContactPicked(data);
}
}
private void onContactPicked(Intent data) {
Cursor cursor = null;
try {
String contact_phoneNo =null;
String contact_name;
Uri uri = data.getData();
cursor = getContentResolver().query(uri, null, null, null, null);
if(cursor != null && cursor.moveToFirst()){
int nameIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
contact_name = cursor.getString(nameIndex);
Integer hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String phone = null;
if (hasPhone > 0) {
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
contact_phoneNo = cursor.getString(phoneIndex);
}
Toast.makeText(this, contact_name+" was added to your urgent contact list", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "phone number: "+contact_phoneNo, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Rereiving contact name works just fine. The problem is with phone number.
The app is not crashing but I see an error in Logcat pointing to contact_phoneNo = cursor.getString(phoneIndex)
Thanks for the help