Read Contacts

How to read contacts in Android and display the results in a list

PDF for offline use
Related Samples:
Related SDKs:
Related Links:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-10

Recipe

Follow these steps to query contacts.

  1. Double-click the project in Visual Studio and navigate to project Properties.
  2. Select the Android Application panel in the Project Options dialog in the Properties navigator in VS.
  3. Click the Add Android Manifest button.
  4. Under Required permissions set the READ_CONTACTS permission and press OK.
  5. Add a file named ContactItemView.axml under the Resources/layout folder containing the following XML.
<?xml version="1.0" encoding="UTF-8" ?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
 android:padding="15dip"/>

In a ListActivity subclass, add the following code to the OnCreate method:

var uri = ContactsContract.Contacts.ContentUri;

string[] projection = { ContactsContract.Contacts.InterfaceConsts.Id,
       ContactsContract.Contacts.InterfaceConsts.DisplayName };

var cursor = ContentResolver.Query(uri, projection, null, null, null);

var contactList = new List<string> ();

if (cursor.MoveToFirst ()) {
       do {
              contactList.Add (cursor.GetString (
                      cursor.GetColumnIndex (projection [1])));
       }  while (cursor.MoveToNext());
}

ListAdapter = new ArrayAdapter<string> (this,
       Resource.Layout.ContactItemView, contactList);

Additional Information

ContactsContract.Contacts is the data contract that is used to interface with contact data. The code queries contacts at the Uri defined by ContactsContract.Contacts.ContentUri, returning the columns selected from ContactsContract.Contacts.InterfaceConsts. It adds the results to List<string> instance that is used to bind to the user interface through an ArrayAdapter.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.