Friday, 30 October 2015

Read Android PhoneBook(native) Contact

I am going to show you how to read list of phone book contact(Name, Email and profile image). This is simple demo to read contacts not a whole implementation. you can integrate below code when you are going to use CursorLoader for Reading contacts.

1.Request Permission to Read the Provider

<uses-permission android:name="android.permission.READ_CONTACTS" />

2.Define the code that sends a query to the provider.

Constructing the query
private static final String[] PROJECTION = new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER,
            ContactsContract.CommonDataKinds.Phone.PHOTO_URI};

Read contact
private void readContact() {
        List<Contact> contacts = new ArrayList<>();
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
        if (cursor != null) {
            try {
                final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                final int uriIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI);
                while (cursor.moveToNext()) {
                    Contact contact = new Contact();
                    contact.setName(cursor.getString(nameIndex));
                    contact.setPhoneNumber(cursor.getString(numberIndex));
                    contact.setUri(cursor.getString(uriIndex));
                    contacts.add(contact);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();
            }
        }
    }

if you added multiple phone number in single contact you can see in list as a separate contact row.






No comments:

Post a Comment