0
votes

I am facing a issue while retrieving contact list from the phone i am getting same contact number for all contact names in Xamarin.Forms. I am new in Xamarin and want to load all phone contacts in listview. Here is my Code:

  private List<ContactMenu> LoadAllContacts()
    {
        List<ContactMenu> getContactNamesAndNumber = new List<ContactMenu>();
        //Bind Contacts
        var forContactNames = ContactsContract.Contacts.ContentUri;
        string[] forContactNumbers = {
        ContactsContract.Contacts.InterfaceConsts.Id,
        ContactsContract.Contacts.InterfaceConsts.DisplayName
    };
        var forContactNumber = ContactsContract.CommonDataKinds.Phone.ContentUri;
        string[] forContactDisplayNumber = { ContactsContract.Contacts.InterfaceConsts.Id, ContactsContract.CommonDataKinds.Phone.Number };
        var names = ManagedQuery(forContactNames, forContactNumbers, null, null, null);
        var nameList = new List<string>();
        var number = ManagedQuery(forContactNumber, forContactDisplayNumber, null, null, null);
        var numbeList = new List<string>();
        if (names.MoveToFirst() && number.MoveToFirst())
        {
            do
            {
                getContactNamesAndNumber.Add(new ContactMenu
                {
                   ContactName =  names.GetString(names.GetColumnIndex(forContactNumbers[1])), ContactNumber = number.GetString(number.GetColumnIndex(forContactDisplayNumber[1]))
                });
                numbeList.Add(number.GetString(number.GetColumnIndex(forContactDisplayNumber[1])));
                nameList.Add(names.GetString(names.GetColumnIndex(forContactNumbers[1])));
            } while (names.MoveToNext());
        }
        ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.ContactItemView, numbeList);
        return getContactNamesAndNumber;
    }

And My Xaml :

 <StackLayout HorizontalOptions="Center">
    <Label Text="Please Select Contact" TextColor="Black" FontFamily="Arial" FontSize="Medium" Font="16"></Label>
    <ListView x:Name="myContacts" HorizontalOptions="Start" ItemTapped="myContacts_ItemTapped">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding ContactName}" DetailColor="Green" TextColor="Black"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>
1

1 Answers

0
votes

You have two ManagedQuerys, names and number but are only advancing the names query via names.MoveToNext() at the end of your do loop.

You should remove one of the ManagedQuery and return all the columns that you need in just one query so you can obtain the name and matching number from the same data row.