Getting only one phone number for contact list

I need to retrieve contact list. All I need is phone numbers and their display names.

First I have to say, that such a simple task is really unexpectedly troublesome.

Second: after some hours of research I managed to write following piece of code:

`public List GetDeviceContacts()
{
var contactsList = new List();

        var nameDictionary = new Dictionary<int, string>();

        var uri = ContactsContract.Contacts.ContentUri;

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

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

        if (cursor.MoveToFirst())
        {
            do
            {
                if (cursor.GetInt(cursor.GetColumnIndex(projection[2]))==1)
                {
                    nameDictionary.Add(cursor.GetInt(cursor.GetColumnIndex(projection[0])), cursor.GetString(cursor.GetColumnIndex(projection[1])));
                }
            } while (cursor.MoveToNext());
        }



        var phoneDictionary = new List<PhoneRecord>();

        var phoneUri = ContactsContract.CommonDataKinds.Phone.ContentUri;

        string[] phoneProjection = { "contact_id", ContactsContract.CommonDataKinds.Phone.Number };

        var phoneCursor = Forms.Context.ApplicationContext.ContentResolver.Query(phoneUri, phoneProjection, null, null, null);

        if (phoneCursor.MoveToFirst())
        {
            do
            {
                phoneDictionary.Add(new PhoneRecord
                {
                    ContactId= phoneCursor.GetInt(phoneCursor.GetColumnIndex(phoneProjection[0])),
                    PhoneNumber= phoneCursor.GetString(phoneCursor.GetColumnIndex(phoneProjection[1]))
                });
            } while (cursor.MoveToNext());
        }



        foreach(var kvp in phoneDictionary)
        {
            if(!nameDictionary.ContainsKey(kvp.ContactId))
            {
                throw new Exception("Phone number with no contact id found!");
            }

            var newContact = new OneContact();

            newContact.DisplayName = nameDictionary[kvp.ContactId];
            newContact.PhoneNumber = kvp.PhoneNumber;

            contactsList.Add(newContact);
        }



        return contactsList;`

Theoretically those queries should give me two lists: one of contacts, and one of phone numbers, that I could link by contact_id. The problem is: second query always gives only one record! And I am stuck, can anybody help me?

Tagged:
Sign In or Register to comment.