Amos
Amos

Reputation: 1351

Android - contact id is not the selected contact out of the intent

When the user needs to select a contact, I call this intent:

Intent pickContactIntent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI );
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);

in onActivityResult I have the following:

Uri pickedContact = intent.getData();
Cursor cursor = getContentResolver().query(pickedContact, null, null, null, null);
   if (cursor.moveToFirst()) {
       contactInfo.name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
       contactInfo.photo = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));

       Cursor pCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                            new String[]{cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))}, null);
}

While the DISPLAY_NAME and the PHOTO_THUMBNAIL_URI are working as expected, the _ID seems to be of a different contact so the phone numbers cursor retrieves irrelevant phone numbers (of a different contact). What am I missing?

Upvotes: 0

Views: 164

Answers (1)

Karakuri
Karakuri

Reputation: 38605

The Uri you specified as the data for the Intent does not match the mimetype you have set.

For the data you used Contacts.CONTENT_URI, which has the mimetype Contacts.CONTENT_TYPE (whose value is "vnd.android.cursor.dir/contact"). For the mimetype, you set it as CommonDataKinds.Phone.CONTENT_TYPE (whose value is "vnd.android.cursor.dir/phone_v2"), which is normally associated with the Uri CommonDataKinds.Phone.CONTENT_URI.

What's happening is you are actually picking a Phone, so you are getting back a content Uri of a Phone instead of a Contact. This is not apparent when you extract the display name and thumbnail photo Uri, because those columns come from the contact anyway when you query for a Phone. However, the _ID is for that of the Phone, not the Contact.

Change your code to

pickContactIntent.setType(Contacts.CONTENT_TYPE)

...or just remove the call to setType() altogether, since the system will resolve it anyway.

Upvotes: 2

Related Questions