3

Following is from Android Documentation

You can acquire a lookup key from the contact itself, it is a column on the ContactsContract.Contacts table.

Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey)

Cursor c = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME},        ...);
try {
c.moveToFirst();
String displayName = c.getString(0);
} finally {
c.close();
}

but couldn't get it to work.

I visited answers on Stackoverflow here and here but in vein.

Any help will be highly appreciated.

Community
  • 1
  • 1
Gaurav Agarwal
  • 18,754
  • 29
  • 105
  • 166

1 Answers1

3

The code in the documentation is related to how to use the lookupKey once you get it, not how to obtain it.

Like they said, you can acquire it from the Contacts table. So, in order to get the lookupKey for each contact in your contacts list, you can use the following projection (the rest of the code provided is only here to show the results, you can use it as you want):

String [] PROJECTION = new String [] {  ContactsContract.Contacts.LOOKUP_KEY };

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, null, null, null);


for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
     Log.d(LOG_TAG, "lookupKey for contact:  " + cursor.getString(1) + ", is: " + cursor.getString(0));
}
Chisko
  • 3,092
  • 6
  • 27
  • 45
Amokrane Chentir
  • 29,907
  • 37
  • 114
  • 158
  • Something wrong with my answer? Always glad to learn new things, but please when you down vote, explain why?! Because I really think this is a good answer to his question since it does provide lookup keys for each contact (I have written the code and tested it). – Amokrane Chentir Mar 04 '12 at 12:49
  • I dont know who downvoted it, I am still trying to understand you answer, once I am done I will comment. – Gaurav Agarwal Mar 04 '12 at 12:53
  • Each contact has a `lookupKey`. The code shown in my answer helps you get that `lookupKey` for each one of them. Don't hesitate to ask for further explanations if it's unclear. – Amokrane Chentir Mar 04 '12 at 12:56
  • 1
    Android Documentation says **If you need to read an individual contact, consider using CONTENT_LOOKUP_URI instead of CONTENT_URI.** [link]http://developer.android.com/reference/android/provider/ContactsContract.Contacts.html But in your answer we are infact using CONTENT_URI to obtain the Display Name. – Gaurav Agarwal Mar 04 '12 at 13:34
  • I think lookupkey in only for one contact. Android documentation "If you need to read an **individual contact**, consider using CONTENT_LOOKUP_URI instead of CONTENT_URI. – Gaurav Agarwal Mar 17 '12 at 21:38
  • Can we register ContentObserver for single contact entry ? I tried it but in onChange() method, i'm not getting the Uri of the changed contact, so that i can query that particular contact. – K Pradeep Kumar Reddy Apr 27 '23 at 07:35