How to get the first name and last name from Android contacts?

bharath picture bharath · Nov 29, 2010 · Viewed 43.2k times · Source

How to get the following fields from Android contacts? I used Android 2.2.

  1. Name prefix
  2. First name
  3. Middle name
  4. Last name
  5. Name prefix
  6. Phonetic given name
  7. Phonetic middle name
  8. Phonetic family name

Answer

Krzysztof Wolny picture Krzysztof Wolny · Jan 5, 2011

Look at ContactsContract.CommonDataKinds.StructuredName class. You can find there all columns you are looking for. Try sth like this:

    String whereName = ContactsContract.Data.MIMETYPE + " = ?";
    String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
    Cursor nameCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
    while (nameCur.moveToNext()) {
        String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
        String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
        String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
    }
    nameCur.close();

It returns all names in contacts. To be more precise you can add a contact id as an additional parameter to the query - you will get address for particular contact.