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.
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));
}