Advertisement
  1. Code
  2. Mobile Development
  3. Android Development

Android Essentials: Using the Contact Picker

Scroll to top
This post is part of a series called Android Essentials.
Android Essentials: Creating Simple User Forms
Android Essentials: Application Preferences

This tutorial will not only show you how to launch the contact picker and get results, but also how to use those results in Android SDK 2.0 and above.

Getting Started

This tutorial will start out simple, but then we’ll get in to some of the technical details of using Contacts with the ContactsContract class, which was introduced in API Level 5. Make sure you have your Android development environment installed and configured correctly. You’re free to build upon any application you have, start a new one from scratch, or follow along using the InviteActivity code in our open source project.

We’ll then be adding functionality to allow a user to choose one of their existing contacts and send a canned message to them. We’re going to dive right in, so have all of your code and tools ready. Finally, make sure your device or emulator has some contacts configured (with names and emails) within the Contacts application.

Step 1: Creating Your Layout

There are two essential form controls necessary for the contact picker to work. First, we need an EditText field where the resulting email will show. Second, we need some way for the user to launch the contact picker. A Button control works well for this.

The following Layout segment has both of these elements defined appropriately:

1
2
<RelativeLayout
3
    android:layout_height="wrap_content"
4
    android:layout_width="match_parent">
5
    <EditText
6
        android:layout_height="wrap_content"
7
        android:hint="@string/invite_email_hint"
8
        android:id="@+id/invite_email"
9
        android:inputType="textEmailAddress"
10
        android:layout_width="wrap_content"
11
        android:layout_toLeftOf="@+id/do_email_picker"
12
        android:layout_alignParentLeft="true"></EditText>
13
    <Button
14
        android:layout_width="wrap_content"
15
        android:layout_height="wrap_content"
16
        android:id="@+id/do_email_picker"
17
        android:text="@string/pick_email_label"
18
        android:layout_alignParentRight="true"
19
        android:onClick="doLaunchContactPicker"></Button>
20
</RelativeLayout>

This layout XML is part of a larger layout. Here’s what it looks like in the layout designer, complete with the string resources filled out:

Using Contact PickerUsing Contact PickerUsing Contact Picker

Step 2: Launching the Contact Picker

Now you need to write the code to handle the Button push, which will launch the contact picker. One of the most powerful features of the Android platform is that you can leverage other applications’ functionality by using the Intent mechanism. An Intent can be used along with the startActivityForResult() method to launch another Android application and retrieve the result. In this case, you can use an Intent to pick a contact from the data provided by the Contacts content provider.

Here’s the implementation of doLaunchContactPicker():

1
2
import android.provider.ContactsContract.Contacts;
3
import android.provider.ContactsContract.CommonDataKinds.Email;
4
5
private static final int CONTACT_PICKER_RESULT = 1001;
6
7
public void doLaunchContactPicker(View view) {
8
    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
9
            Contacts.CONTENT_URI);
10
    startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
11
}

Note: The import commands are important here. Make sure you’re using the Contacts class from the ContactsContract and not the older android.provider.Contacts one.

Once launched, the contacts picker in your application will look something like this:

Using Contact PickerUsing Contact PickerUsing Contact Picker

Step 3: Handling the Results

Now you are ready to handle the results of the picker. Once the user taps on one of the contacts in the picker, focus will return to the calling Activity (your application’s Activity). You can grab the result from the contacts picker by implementing the onActivityResult() method of your Activity. Here you can check that the result matches your requestCode and that the result was good. Your onActivityResult() method implementation should be structured like this:

1
2
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
3
        if (resultCode == RESULT_OK) {
4
            switch (requestCode) {
5
            case CONTACT_PICKER_RESULT:
6
                // handle contact results
7
                break;
8
            }
9
10
        } else {
11
            // gracefully handle failure
12
            Log.w(DEBUG_TAG, "Warning: activity result not ok");
13
        }
14
    }

You’ll get a result other than RESULT_OK if the user cancels the operation or if something else goes wrong.

Step 4: Reading the Result Data

The final parameter to onActivityResult is an Intent called “data.” This parameter contains the results data we are looking for. Different Intents will return different types of results. One option for inspecting the results is to display everything found in the Extras bundle in addition to the data Uri. Here’s a code snippet that will show all of the Extras, should any exist:

1
2
Bundle extras = data.getExtras();
3
Set keys = extras.keySet();
4
Iterator iterate = keys.iterator();
5
while (iterate.hasNext()) {
6
    String key = iterate.next();
7
    Log.v(DEBUG_TAG, key + "[" + extras.get(key) + "]");
8
}
9
Uri result = data.getData();
10
Log.v(DEBUG_TAG, "Got a result: "
11
    + result.toString());

We’re not really interested in the Extras bundle for the contacts picker because it doesn’t contain the information we need. We just want the Uri which will lead us to the important contact details.

Step 5: Understanding the Result

In the onActivityResult() callback, we are supplied the Uri to the specific contact that the user chose from the contact picker. Using this Uri directly would allow us to get the basic Contact data, but no details. However, we are interested in determining the email address of the contact. So, an easy way to deal with this is to just grab the contact id from the Uri, which is the number at the end of the path:

The full Uri looks something like:

content://com.android.contacts/contacts/lookup/0r7-2C46324E483C324A3A484634/7

In this case, the resulting id would simply be 7.
We can retrieve the contact identifier using the getLastPathSegment() method, as follows:

1
2
// get the contact id from the Uri
3
String id = result.getLastPathSegment();

Step 6: Querying the Contacts Database for Email

Now that you have the identifier for the chosen contact, you have all the information you need to query the Contacts content provider directly for that contact’s email address. Android content providers are a powerful way of sharing data amongst applications. The interface to them is similar to that of a database and many are database backed, using SQLite, but they need not be.

One way you can query the contacts content provider for the appropriate contact details is by using the default ContentResolver with one of the ContactsContract.CommonDataKinds subclasses. For email, you can use the ContactsContract.CommonDataKinds.Email class as follows:

1
2
// query for everything email
3
cursor = getContentResolver().query(
4
        Email.CONTENT_URI, null,
5
        Email.CONTACT_ID + "=?",
6
        new String[]{id}, null);

Some other useful ContactsContract.CommonDataKinds subclasses include Phone, Photo, Website, Nickname, Organization, and StructuredPostal.

Step 7: Viewing the Query Results

Certainly, you could read the class documentation for the ContactsContract.CommonDataKinds.Email class and determine what kind of results to expect. However, this is not always the case so let’s inspect the results of this call. This is a very handy trick if you are working with a content provider that has less-than-adequate documentation, or is not behaving as expected.

This snippet of code will show you, via LogCat output, every column and value that is returned from the query to the content provider:

1
2
cursor.moveToFirst();
3
String columns[] = cursor.getColumnNames();
4
for (String column : columns) {
5
    int index = cursor.getColumnIndex(column);
6
    Log.v(DEBUG_TAG, "Column: " + column + " == ["
7
            + cursor.getString(index) + "]");

Now you can see that, indeed, they really did mean for the email to come back via a column called DATA1, aliased to Email.DATA. The Android Contacts system is very flexible, and this sort of generic column name shows where some of that flexibility comes from. The email type, such as Home or Work, is found in Email.TYPE.

Step 8: Retrieving the Email

We have all of the data we need to actually get the email address, or addresses, of the contact picked by the user. When using database Cursors, we have to make sure they are internally referencing a data row we’re interested in, so we start with a call to the moveToFirst() method and make sure it was successful. For this tutorial, we won’t worry about multiple email addresses. Instead, we’ll just use the first result:

1
2
if (cursor.moveToFirst()) {
3
    int emailIdx = cursor.getColumnIndex(Email.DATA);
4
    email = cursor.getString(emailIdx);
5
    Log.v(DEBUG_TAG, "Got email: " + email);
6
}

It’s important to remember that a contact may have many addresses. If you wanted to give the user the option of choosing from multiple email addresses, you could display your own email chooser to pick amongst these after the user has chosen a specific contact.

Step 9: Updating the Form

After all that work to get the email address, don’t forget to update the form. You might also consider informing the user if the contact didn’t have any email address listed.

1
2
EditText emailEntry = (EditText)findViewById(R.id.invite_email);
3
emailEntry.setText(email);
4
if (email.length() == 0) {
5
    Toast.makeText(this, "No email found for contact.", Toast.LENGTH_LONG).show();
6
}

And there it is:

Content PickerContent PickerContent Picker

Step 10: Putting it All Together

We skipped over two important items in this tutorial that are worth mentioning now.

First, we didn’t include any error checking; we did this for clarity, but in production code, this is an essential piece of the solution. An easy way to implement some checking would be to to wrap just about everything in a try-catch block.

Second, you need to remember that Cursor objects require management within your Activity lifecycle. Always remember to release Cursor objects when you are done using them.

Here’s the complete implementation of the onActivityResult() method to put these points in perspective:

1
2
@Override
3
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
4
    if (resultCode == RESULT_OK) {
5
        switch (requestCode) {
6
        case CONTACT_PICKER_RESULT:
7
            Cursor cursor = null;
8
            String email = "";
9
            try {
10
                Uri result = data.getData();
11
                Log.v(DEBUG_TAG, "Got a contact result: "
12
                        + result.toString());
13
14
                // get the contact id from the Uri
15
                String id = result.getLastPathSegment();
16
17
                // query for everything email
18
                cursor = getContentResolver().query(Email.CONTENT_URI,
19
                        null, Email.CONTACT_ID + "=?", new String[] { id },
20
                        null);
21
22
                int emailIdx = cursor.getColumnIndex(Email.DATA);
23
24
                // let's just get the first email
25
                if (cursor.moveToFirst()) {
26
                    email = cursor.getString(emailIdx);
27
                    Log.v(DEBUG_TAG, "Got email: " + email);
28
                } else {
29
                    Log.w(DEBUG_TAG, "No results");
30
                }
31
            } catch (Exception e) {
32
                Log.e(DEBUG_TAG, "Failed to get email data", e);
33
            } finally {
34
                if (cursor != null) {
35
                    cursor.close();
36
                }
37
                EditText emailEntry = (EditText) findViewById(R.id.invite_email);
38
                emailEntry.setText(email);
39
                if (email.length() == 0) {
40
                    Toast.makeText(this, "No email found for contact.",
41
                            Toast.LENGTH_LONG).show();
42
                }
43
44
            }
45
46
            break;
47
        }
48
49
    } else {
50
        Log.w(DEBUG_TAG, "Warning: activity result not ok");
51
    }
52
}

You’ve now got everything you need to complete the application. Remember, though, that if you’re working with real data, take care not to spam your friends too much. ☺

Conclusion

In this tutorial, you’ve learned how to launch the Contacts picker and retrieve the chosen result. You also learned how to inspect the results and retrieve the email address for the picked contact using the contacts content provider. You can use this method to retrieve all sorts of information about a given contact.

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.