Read Contact Names from Android Mobile using Visual Studio Xamarin Android

In this article, we discuss how to read contact names from Android mobile using Xamarin Android app. Open Microsoft Visual Studio 2017, create new Blank Android application and name it as AccessContactsAndroid.

Add TextView to your Main.axml form as below.

Main.axml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="match_parent"

    android:scrollbars="vertical"

    android:layout_height="match_parent">

  <TextView

      android:text="Text"

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:scrollbars="vertical"

      android:id="@+id/txtContacts" />

</LinearLayout>

Now change the OnCreate() method in MainActivity.cs class as shown below.

protected override void OnCreate(Bundle bundle)

{

            base.OnCreate(bundle); 

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

            SetContentView(Resource.Layout.Main); 

            var uri = ContactsContract.Contacts.ContentUri; 

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

            ContactsContract.Contacts.InterfaceConsts.DisplayName }; 

            var cursor = ManagedQuery(uri, projection, null, null, null);         

            var contactList = new List<string>(); 

            if (cursor.MoveToFirst())

            {

                do

                {

                    string name = cursor.GetString(cursor.GetColumnIndex(projection[1]));                  

                        contactList.Add(name);                   

                } while (cursor.MoveToNext());

            } 

            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;

}

As shown above we are using ContactsContract.Contacts.ContentUri to read the contacts from Android mobile.

Before deploying the application to mobile, right-click on project and select properties. Select Android Manifest tab and select READ_CONTACTS permission under Required Permissions as shown below.

Now connect your mobile using USB cable and select your mobile from the emulator list on Visual Studio. Run the application and open AccessContactsAndroid app from your mobile. It displays your contact list as shown below.