Search code examples
androidandroid-intentandroid-contentprovidercontactscontract

How to get LOOKUP_KEY of a Contact from ContactsContract.Contacts?


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


Solution

  • 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();
    }