Archive‎ > ‎Fall 2009‎ > ‎Course Project‎ > ‎Buddy Suite‎ > ‎Tutorial #3‎ > ‎

ContactsViewer

Get the ContentResolver from the application context and use it to execute a query against the Content Provider that contains your contact list.

Getting the ContentResolver

ContentResolver resolver = context.getContentResolver();
Cursor cursor = resolver.query(People.CONTENT_URI, null, null, null,null);

The returned Cursor is a managed way of controlling the current position (row) in the query's result set. You can use a set of getter methods to extract values for each column in the current row. The People class offers convenience properties for each of the column indexes.

Getting the columns for name and unique ID

int nameIndex = cursor.getColumnIndexOrThrow(People.NAME);
int personID = cursor.getColumnIndexOrThrow(People._ID);

Iterate over the result set, extracting the name and address of each contact.

Getting name and ID

if (cursor.moveToFirst()) {
            String name = cursor.getString(nameIndex);
            String id = cursor.getString(personID);

We have a Contact's name now. Next, we need to build a new query to retrieve the email address.

Getting the email address

            String where = Contacts.ContactMethods.PERSON_ID + " == " + id
                    + " AND " + Contacts.ContactMethods.KIND + " == "
                    + Contacts.KIND_EMAIL;
            Cursor c = context.getContentResolver().query(
                    Contacts.ContactMethods.CONTENT_URI, null, where, null,
                    null);
            int emailIndex = c                   .getColumnIndexOrThrow(Contacts.ContactMethodsColumns.DATA);
            String email = "";
            if (c.moveToFirst()) {
                email = c.getString(emailIndex);
            }
            c.close();

Finally, we close the first cursor.

Finishing

        }
        cursor.close();

Before Android lets you casually flip through the user's contact list you need to get permission. Permissions are a security mechanism that lets users decide what risks they're willing to take with a new app – kind off like UAC but without the continuous, repetitive, soul-destroying inevitability of UAC. Your AndroidManifest.xml file should have the <uses-permission android:name="android.permission.READ_CONTACTS" /> permission.