I am trying to find a contact by display name. The goal is to open this contact and add more data to it (in particular, more phone numbers), but I'm struggling to find the contact I want to update.
This is the code I'm using:
public static String findContact(Context context) { ContentResolver contentResolver = context.getContentResolver(); Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI; String[] projection = new String[] { PhoneLookup._ID }; String selection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ?"; String[] selectionArguments = { "John Johnson" }; Cursor cursor = contentResolver.query(uri, projection, selection, selectionArguments, null); if (cursor != null) { while (cursor.moveToNext()) { return cursor.getString(0); } } return "John Johnson not found"; }
I have a contact called "John Johnson", but the method always returns "not found." I also tried to find a contact with only one name, so it does not matter.
I suspect that something is wrong with the uri, select or select arguments, because I could not find a single example of online searching for contacts with a given display name, and it seems that the display name is a special kind of information, for example, a phone number .
Any ideas how I can get to find John Johnson?
UPDATE: I found out how to find a contact by display name:
ContentResolver contentResolver = context.getContentResolver(); Uri uri = Data.CONTENT_URI; String[] projection = new String[] { PhoneLookup._ID }; String selection = StructuredName.DISPLAY_NAME + " = ?"; String[] selectionArguments = { "John Johnson" }; Cursor cursor = contentResolver.query(uri, projection, selection, selectionArguments, null); if (cursor != null) { while (cursor.moveToNext()) { return cursor.getString(0); } } return "John Johnson not found";
This code returns the contact identifier of the first contact with the display name "John Johnson". In my source code, I had the wrong uri and the wrong choice in my request.
android android-contentresolver
Bjarte aune olsen
source share