Xamarin.Tip – Read All Contacts in Android

To follow the posts made for iOS, let’s talk about reading the device contacts in Xamarin.Android.

Since Xamarin hasn’t been working on the Xamarin.Mobile component for a while, and James Montemagno dropped support for his Contacts Plugin, if you want to access the contact APIs on each platform, you might just have to go at it yourself – or just copy this code!

Android

The first thing we need to do is create our shared model to represent a contact on the device. In this example, we’ll focus on just the name and phone number of a given contact:
PhoneContact.cs

public class PhoneContact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
 
    public string Name { get => $"{FirstName} {LastName}"; }
 
}

Now we need to create our service to enable the reading of the contacts on the device. We’ll call it the ContactService.

    public class ContactService_Android
    {
        public IEnumerable<PhoneContact> GetAllContacts()
        {
            var phoneContacts = new List<PhoneContact>();

            using (var phones = Android.App.Application.Context.ContentResolver.Query(ContactsContract.CommonDataKinds.Phone.ContentUri, null, null, null, null))
            {
                if (phones != null)
                {
                    while (phones.MoveToNext())
                    {
                        try
                        {
                            string name = phones.GetString(phones.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.DisplayName));
                            string phoneNumber = phones.GetString(phones.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.Number));

                            string[] words = name.Split(' ');
                            var contact = new PhoneContact();
                            contact.FirstName = words[0];
                            if (words.Length > 1)
                                contact.LastName = words[1];
                            else
                                contact.LastName = ""; //no last name
                            contact.PhoneNumber = phoneNumber;
                            phoneContacts.Add(contact);
                        }
                        catch (Exception ex)
                        {
                            //something wrong with one contact, may be display name is completely empty, decide what to do
                        }
                    }
                    phones.Close(); 
                }
                // if we get here, we can't access the contacts. Consider throwing an exception to display to the user
            }

            return phoneContacts;
        }
    }

 
In this method, we get access to the Context‘s ContentResolver and query for all contacts’ phone numbers.

We can then iterate over each phone number and read their name and number which is added to the master list of PhoneContacts. This list is what ends up being returned, and we close the query context we opened in the using statement.

There is one more step we need to do in order to access the contacts on the device. In the AndroidManifest.xml we need to add the permission for READ_CONTACTS. This can be added in the XML directly or done in the UI from Visual Studio:
Screen Shot 2017-09-07 at 5.30.01 PM
 
Now that we have access to all the contacts on the device, we can render those in a list through either an Android ListView, RecyclerView, or if in Xamarin.Forms – a Xamarin.Forms.ListView.

Screenshot_1504821136

 Try building some other fun features into your ContactsService or selector!
– Filter the list via search
– Build a more user friendly selector without duplicating contacts
– Gather additional properties for contacts

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Advertisements

One thought on “Xamarin.Tip – Read All Contacts in Android”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s