How to Look-Up a Contact's Name from Their Phone Number on Android

Android: Retrieve contact name from phone number

For that you need to use the optimized PhoneLookup provider as described.

Add the permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Then:

public String getContactName(final String phoneNumber, Context context)
{
Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));

String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};

String contactName="";
Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);

if (cursor != null) {
if(cursor.moveToFirst()) {
contactName=cursor.getString(0);
}
cursor.close();
}

return contactName;
}

How to search contacts by name and phone number?

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

Searching for a contact using phone number

Try:

String selection = "REPLACE (" + ContactsContract.CommonDataKinds.Phone.NUMBER + ", \" \" , \"\" ) = ?";

See replace function.

Search contact by phone number

You should have a look at the recommended ContactsContract.PhoneLookup provider

A table that represents the result of looking up a phone number, for example for caller ID. To perform a lookup you must append the number you want to find to CONTENT_FILTER_URI. This query is highly optimized.

Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME,...

Get contact name given a phone number in Android

Use reflections instead of comparing sdk version.

public String getContactName(final String phoneNumber) 
{
Uri uri;
String[] projection;
mBaseUri = Contacts.Phones.CONTENT_FILTER_URL;
projection = new String[] { android.provider.Contacts.People.NAME };
try {
Class<?> c =Class.forName("android.provider.ContactsContract$PhoneLookup");
mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri);
projection = new String[] { "display_name" };
}
catch (Exception e) {
}

uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);

String contactName = "";

if (cursor.moveToFirst())
{
contactName = cursor.getString(0);
}

cursor.close();
cursor = null;

return contactName;
}


Related Topics



Leave a reply



Submit