0

I am trying to create a function that will take a String as an argument and it will return the Contact_ID for the contact that has a phone number like the String provided.

I have already found the following code

private String getContactName (String number) 
{
    String contactName = "";
    ContentResolver context = getContentResolver();

    /// number is the phone number
    Uri lookupUri = Uri.withAppendedPath(
    PhoneLookup.CONTENT_FILTER_URI, 
    Uri.encode(number));

    String[] mPhoneNumberProjection = { PhoneLookup._ID, PhoneLookup.NUMBER, PhoneLookup.DISPLAY_NAME };

    Cursor cur = context.query(lookupUri,mPhoneNumberProjection, null, null, null);
    try 
    {
       if (cur.moveToFirst()) 
       {
          contactName = cur.getString(2);
          return contactName;
       }
    } 
    finally 
    {
        if (cur != null)
            cur.close();
    }
    return contactName;
}

It returns all contactsName for a given number. How i can get the contact id from here?

Thanks!

user2116122
  • 13
  • 1
  • 7
  • Have a look at this class: http://developer.android.com/reference/android/provider/ContactsContract.PhoneLookup.html – rciovati Feb 27 '13 at 16:07
  • Thanks for the quick response! Could you provide me some example code? – user2116122 Feb 27 '13 at 16:10
  • You can fine some code here: http://stackoverflow.com/questions/2174048/how-to-look-up-a-contacts-name-from-their-phone-number-on-android – rciovati Feb 27 '13 at 16:23

1 Answers1

0

You simply have to replace cur.getString(2) with cur.getString(0). You already have the _ID as part of your projection (which BTW could be reduced to just the _ID).

Wolfram Rittmeyer
  • 2,402
  • 1
  • 18
  • 21