Read Contacts for Android Mobile using Xamarin.Mobile Component

In my previous article we discussed how to read contacts using Xamarin Android. Today we discuss how to read contacts using Xamarin.Mobile component in Microsoft Visual Studio 2017.

Open Visual Studio 2017, create new Android blank application and add reference to Xamarin.Mobile component.

Add below GetContacts() method to MainActivity.cs class as shown below.

using Android.App;

using Android.OS;

using Android.Widget;

using System.Collections.Generic;

 

namespace ReadContactsAndroid

{

    [Activity(Label = "ReadContactsAndroid", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity

    {

        public List<string> GetContacts()

        {

            var book = new Xamarin.Contacts.AddressBook(Application.Context);

 

            var contactList = new List<string>();

            foreach (var contact in book)

            {

                string sName = contact.DisplayName;

                string sNumber = string.Empty;

 

                foreach (var phone in contact.Phones)

                {

                    sNumber = sNumber + "," + phone.Number;

                }

 

                contactList.Add(sName + sNumber);

            }

            return contactList;

        }

 

        protected override void OnCreate(Bundle bundle)

        {

            base.OnCreate(bundle);

 

            // Set our view from the "main" layout resource

            SetContentView(Resource.Layout.Main);

 

            var contactList = GetContacts();

            contactList.Sort();

 

            TextView txtContactList = FindViewById<TextView>(Resource.Id.txtContacts);

            string sContactsList = string.Empty;

 

            foreach (string strName in contactList)

            {

                sContactsList = sContactsList + "\r\n" + strName;

            }

            txtContactList.Text = sContactsList;

        }

    }

}

 

To read contacts we are calling Xamarin.Contacts.AddressBook by passing Application.Context as input parameter.

To read contacts from Android mobile, we must enable READ_CONTACTS by modifying the AndroidManifest.xml file. To do that, right-click on project and select properties. Select Android Manifest tab and select READ_CONTACTS permission under Required Permissions section.

Now connect Android mobile to system and select that specific Android mobile emulator. Deploy the application to mobile through Build option. Application displays all contact details from your phone in the TextView control.

                                                                                              Download Source Code