testivanivan
testivanivan

Reputation: 1514

Android. Retrieve first name and last name from contact book by phone number

I am trying to get first name and last name in contact book by phone number. Here is my code:

  Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
  Cursor cursor = cResolver.query(uri, null, null, null, null); 
  if(cursor != null && cursor.moveToFirst()) {
            int idColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            int firstNameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
            int lastNameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME);
            while (!cursor.isAfterLast()) {
                long id = cursor.getLong(idColumnIndex);
                contact = new  MyContact();
                contact.setId(id);
                contact.setFirstName(cursor.getString(firstNameIndex));
                contact.setLastName(cursor.getString(lastNameIndex));
            }
            cursor.close();
        }

But firstNameIndex and lastNameIndex is always -1. What I am doing wrong ? Please help me.

Upvotes: 0

Views: 391

Answers (1)

marmor
marmor

Reputation: 28179

PhoneLookup is a nice and quick way to get contact data by a phone number, but it returns a cursor limited to the columns mentioned in the docs.

You can see there's DISPLAY_NAME you can access, but not GIVEN_NAME, FAMILY_NAME.

GIVEN_NAME & FAMILY_NAME are fields stored in the Data table, which means you need to query that table separately to get to those fields.

So, you can just add another query using the contact ID you got from PhoneLookup (note that for each looked up phone there might be multiple contacts returned).

Here's a sample method to get first/last names from contact ID:

private void addNames(MyContact contact, long contactId) {
    String[] projection = new String[] {StructuredName.GIVEN_NAME, StructuredName.FAMILY_NAME};
    
    // filter to just StructuredName rows from the data table for the given contact
    String selection = Data.CONTACT_ID + "=" + contactID + " AND " + Data.MIMETYPE + "=" + StructuredName.CONTENT_ITEM_TYPE;
    
    Cursor cursor = getContentResolver().query(Data.CONTENT_URI, projection, selection, null, null);
    if (cursor.next()) {
        contact.setFirstName(cursor.getString(0));
        contact.setLastName(cursor.getString(1));
    }
    cursor.close();
}

Upvotes: 1

Related Questions