10

I am trying to retrieve contact names given the contact phone number. I made a function that should work in all API versions, by I can't make it work in 1.6 and I can't see the problem, maybe someone can spot it?

Note that, I've replaced the API constants for strings so I don't have deprecated warning problems.

public String getContactName(final String phoneNumber) 
{  
    Uri uri;
    String[] projection;

    if (Build.VERSION.SDK_INT >= 5)
    {
        uri = Uri.parse("content://com.android.contacts/phone_lookup");
        projection = new String[] { "display_name" };
    }
    else
    { 
        uri = Uri.parse("content://contacts/phones/filter");
        projection = new String[] { "name" }; 
    } 

    uri = Uri.withAppendedPath(uri, 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; 
}
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
PerracoLabs
  • 16,449
  • 15
  • 74
  • 127
  • 1
    Don't support 1.6 anymore! http://developer.android.com/resources/dashboard/platform-versions.html. It makes up for only 2.2% of the current user base and that number will shrink, shrink, shrink. It may never hit zero, but that's only because of technology laggards that aren't going to hear about your new bleeding edge app anyway! Don't waste your time! – Thomas Dignan Jul 17 '11 at 00:23
  • For the facility of others, I have written a post which contains the whole code to query name, photo, contact ID, etc. with decent explanation. The code contains snippets as found on different answers, but more organized and tested. Link: http://hellafun.weebly.com/home/get-information-of-a-contact-from-number – Usman May 02 '17 at 15:08

4 Answers4

21

This seems to work fine in the latest versions:

private String getContactName(Context context, String number) {

    String name = null;

    // define the columns I want the query to return
    String[] projection = new String[] {
            ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.PhoneLookup._ID};

    // encode the phone number and build the filter URI
    Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));

    // query time
    Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);

    if(cursor != null) {
        if (cursor.moveToFirst()) {
            name =      cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
            Log.v(TAG, "Started uploadcontactphoto: Contact Found @ " + number);            
            Log.v(TAG, "Started uploadcontactphoto: Contact name  = " + name);
        } else {
            Log.v(TAG, "Contact Not Found @ " + number);
        }
        cursor.close();
    }
    return name;
}
StarNix
  • 390
  • 3
  • 7
  • 1
    Thanks it works, but if you gonna get a lot of names, you should make it in asyncTask to avoid not responding error due to much loading in the main thread. – Aziz Apr 09 '14 at 12:10
9

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; 
}
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
user936414
  • 7,574
  • 3
  • 30
  • 29
  • Hello, I tried something similar, but it didn't work. Here is my question, I would really appreciate your help! :) http://stackoverflow.com/questions/35097844/get-contact-name/35098111#35098111 – Ruchir Baronia Jan 30 '16 at 05:06
1
public static String getContactName(Context context, String phoneNumber)
{
    ContentResolver cr = context.getContentResolver();
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
    if (cursor == null)
    {
        return null;
    }
    String contactName = null;
    if(cursor.moveToFirst()) 
    {
        contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
    }

    if(cursor != null && !cursor.isClosed()) {
        cursor.close();
    }

    return contactName;
}
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
Afzaal Iftikhar
  • 233
  • 2
  • 5
0
 private String getContactNameFromNumber(String number) { 
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));


Cursor cursor = context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null);
if (cursor.moveToFirst())
{
    name = cursor.getString(cursor.getColumnIndex(PhoneLookup.D