1

I have to select a Contact from an android device Contacts list.

With the following code I retrieve an activity with the list of the contacts on the device:

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, ADD_CONTACT_REQUEST_CODE);

After picking a contact, how can I get the LOOKUP_KEY of the selected contact?

Instead or retrieving content://com.android.contacts/contacts/lookup/0r2-334B29432‌​D314D2D29/2, I need to get 0r2-334B29432‌​D314D2D29, that is the LOOKUP_KEY

So far I'm able just to retrieve full Uri

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if(resultCode == Activity.RESULT_OK){
      switch (requestCode){
          case ADD_CONTACT_REQUEST_CODE:
             Uri contactUri = data.getData();
             String contactUriString = contactUri.toString();
             break;
      }
   }
}

Thank You in advance

MDP
  • 4,177
  • 21
  • 63
  • 119

1 Answers1

4

There's a simple API helper method for this - getLookupUri:

Uri contactUri = data.getData();
ContentResolver cr = getContentResolver();
Uri lookupUri = ContactsContract.Contacts.getLookupUri(cr, contactUri);

Update

To get the LOOKUP_KEY, do this:

String projection = String[] { Contacts.LOOKUP_KEY };
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);

if (cursor != null && cursor.moveToNext()) {
  String lookupKey = cursor.getString(0);
  Log.d(TAG, "key = " + lookupKey);
  cursor.close();
}
marmor
  • 27,641
  • 11
  • 107
  • 150
  • 1
    Thank you very very very much :) – MDP Jun 12 '17 at 07:34
  • I tried using your way but it seems that data.getData(); and ContactsContract.Contacts.getLookupUri(cr, contactUri) give the same URI, that is always something like content://com.android.contacts/contacts/lookup/0r2-334B29432D314D2D29/2 – MDP Jun 12 '17 at 08:36
  • that's your lookupUri. what are you trying to do with it? – marmor Jun 12 '17 at 09:51