Warm tip: This article is reproduced from serverfault.com, please click

How to search contacts by name and phone number?

发布于 2021-02-10 19:34:59

I am using Contacts.CONTENT_FILTER_URI to search for contacts.

Uri contentUri = Uri.withAppendedPath(
                ContactsContract.Contacts.CONTENT_FILTER_URI,
                Uri.encode(searchString));

The searchstring can be either a number or a name. That works great.
My only problem is that the result does not contain a contact phone number.

I know that I can get it by querying ContactsContract.Data.CONTENT_URI. However, I would like to find a solution that will give me a contact name and phone number with a single query.

Questioner
Ilya Gazman
Viewed
0
marmor 2021-02-11 04:43:10

You should use Phone.CONTENT_FILTER_URI instead of Contacts.CONTENT_FILTER_URI

Docs say:

The filter is applied to display names as well as phone numbers.

Try this:

Uri filterUri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(searchString));
String[] projection = new String[]{ Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor cur = getContentResolver().query(filterUri, projection, null, null, null);