3

I am reading the contacts data from the android phonebook through my application. I need to read Contact's First Name (GIVEN_NAME), Last Name (FAMILY_NAME), and Phone Number. To do this, I am current reading a Contacts._ID and from that I am reading its First Name and Last Name. Is it possible to get both these fields along with Contacts._ID?

ContentResolver contentResolver = getContentResolver();
Cursor cursor1, cursor2;
String contactID, givenName = "", familyName = "";
String[] projection1 = {ContactsContract.Contacts._ID, ContactsContract.Contacts.HAS_PHONE_NUMBER};
cursor1 = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, projection1, null, null, ContactsContract.Contacts.DISPLAY_NAME);
if (cursor1.getCount() > 0) {
    while (cursor1.moveToNext()) {
        contactID = cursor1.getString(cursor1.getColumnIndex(ContactsContract.Contacts._ID));
        if (cursor1.getInt(cursor1.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
            cursor2 = contentResolver.query(
                ContactsContract.Data.CONTENT_URI,
                new String[]{
                    ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
                    ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME},
                ContactsContract.Data.MIMETYPE + " = ? AND " +
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                new String[]{
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, contactID},
                ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME
            );
            cursor2.moveToNext();
            givenName = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
            familyName = cursor2.getString(cursor2.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
            cursor2.close();
            Toast.makeText(this, givenName + "\n" + familyName, Toast.LENGTH_LONG).show();
            //TODO Code to get Phone Numbers using contactID
        }
    }
}
Shripal Gandhi
  • 126
  • 2
  • 9

0 Answers0