Retrieving Android Contacts

If you are developing a social networking app, or something similar (and who isn’t!), then you might need to retrieve contacts. There are several samples out there that do something like this (sample code in MonoDroid):

private void PopulateContacts()
{
   var uri = ContactsContract.Contacts.ContentUri;
   var cursor = ManagedQuery(uri, null, null, null, null);
   while (cursor.MoveToNext())
   {
      var contactId = cursor.GetString(cursor.GetColumnIndex(BaseColumns.Id));
      txtContacts.Text += System.Environment.NewLine + "Id = " + contactId;
      txtContacts.Text += System.Environment.NewLine + "Name = " +       cursor.GetString(cursor.GetColumnIndex(ContactsContract.ContactsColumns.DisplayName));
      var emailCursor = ManagedQuery(ContactsContract.CommonDataKinds.Email.ContentUri, null, "CONTACT_ID" + " = " + contactId, null, null);
      while (emailCursor.MoveToNext())
      {
         var email = emailCursor.GetString(emailCursor.GetColumnIndex("DATA1"));
         txtContacts.Text += System.Environment.NewLine + "Email: " + email;
       }
      emailCursor.Close();
      txtContacts.Text += System.Environment.NewLine;
   }
   cursor.Close();
}

Continue reading