Chapter 18. Communication, Identity, Sync, and Social Media

One of the primary data types that is stored and used (and reused) in Android is contact data. This consists of the various pieces of information associated with a contact—name, phone number, email, and so on. In Android 2.0 (API level 5), contact data was significantly expanded (allowing access to multiple accounts and support for aggregation of similar contacts). In earlier chapters we covered the use of content providers and Android database classes, so we will not cover that preliminary material in this chapter. Instead, we will focus on the use of the ContactsContract content provider.

Account Contacts

To access the account contacts the following permissions must be provided in the manifest:

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

Within an Activity, we can use the managedQuery method to query the ContactsContract.Contacts data and return a Cursor for our use:

    private Cursor getContacts() {
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        
        String[] projection = new String[] {
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.LOOKUP_KEY,
                ContactsContract.Contacts.DISPLAY_NAME
        };
        
        String selection = null;
        String[] selectionArgs = null;
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + 
                                                        " COLLATE LOCALIZED ASC";

        return managedQuery(uri, projection ...

Get Programming Android, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.