Update a Picker when getting data from DB using an API

kcriswellkcriswell Member ✭✭

I am playing around with an app to test concepts, I am creating a sports registration app that will allow the user to select a participant and then register them for a sport that falls in line with the participants age and gender. IF the person in question is not listed then they can add them. That is where my issue occurs. I get the data from the DB using an API. Then it populates a picker. My issue is that i can't seem to get the picker to refresh after they add a participant. I tried and observableCollection but could not get it to populate when using the API, (had to hard code the values) Here is my code, if you could give me a hand i would appreciate it. using xamarin 3.0.

using Newtonsoft.Json;
using SportsRegTestApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace SportsRegTestApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SelectParticipant : ContentPage
{
public string uri = "...";
List participantList = new List();
HttpResponseMessage response = new HttpResponseMessage();
private ActivityIndicator _activityIndicator = new ActivityIndicator();
HttpClient client = new HttpClient();
string lwaid;
List names = new List();

    public SelectParticipant(string id)
    {
        InitializeComponent();


        lwaid = id;
        uri += id;
        while (IsBusy == true)
        {
            var indicator = new ActivityIndicator { IsRunning = true };
        }

    }

    private async void PopulatePicker()
    {

        response = await client.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            participantList.Clear();
            var content = await response.Content.ReadAsStringAsync();
            participantList = JsonConvert.DeserializeObject<List<Participant>>(content);

            ParticipantNames();
            PickLoading.IsVisible = false;
            ParticipantPicker.IsVisible = true;
            Add.IsVisible = true;
        }

    }


    private void ParticipantNames()
    {
        names.Clear();
        // var index = 0;

        foreach (var person in participantList)
        {
            names.Add(person.firstname + " " + person.middleinitial + " " + person.lastname + " Age:" + ((int.Parse(DateTime.Now.ToString("yyyyMMdd")) - int.Parse(person.dateofbirth.ToString("yyyyMMdd"))) / 10000));
            //index++;
        }

        ParticipantPicker.ItemsSource = names;

    }

    public async void LoadAdd()
    {
        var AddParticipant = new AddPage(lwaid);
        await Navigation.PushModalAsync(AddParticipant, true);

    }

    public async void LoadSports()
    {
        Participant selected = new Participant();
        var i = ParticipantPicker.SelectedIndex;
        if (i >= 0)
        {
            selected = participantList[i];

            var AvailableSports = new AvailableSports(selected);
            await Navigation.PushModalAsync(AvailableSports, true);

            ErrorMsg.IsVisible = false;
            ErrorMsg.Text = "";
        }
        else
        {
            ErrorMsg.Text = "You must choose a participant...";
            ErrorMsg.IsVisible = true;
        }


    }

    protected override void OnAppearing()
    {
        PickLoading.IsVisible = true;
        ParticipantPicker.IsVisible = false;
        Add.IsVisible = false;
        PopulatePicker();
    }

}

}

Best Answer

  • kcriswellkcriswell ✭✭
    edited May 2018 Accepted Answer

    Got it to work, Here is my code so others can see what i did.

        namespace SportsRegTestApp
        {
            [XamlCompilation(XamlCompilationOptions.Compile)]
            public partial class SelectParticipant : ContentPage
            {
                public string uri = "...";
                List<Participant> participantList = new List<Participant>();
                HttpResponseMessage response = new HttpResponseMessage();
                private ActivityIndicator _activityIndicator = new ActivityIndicator();
                HttpClient client = new HttpClient();
                string lwaid;
                public ObservableCollection<string> Items { get; set; }
    
                public SelectParticipant(string id)
                {
                    InitializeComponent();
    
    
                    lwaid = id;
                    uri += id;
                    while (IsBusy == true)
                    {
                        var indicator = new ActivityIndicator { IsRunning = true };
                    }
    
                }
    
                private async void PopulatePicker()
                {
    
                    response = await client.GetAsync(uri);
                    if (response.IsSuccessStatusCode)
                    {
                        participantList.Clear();
                        var content = await response.Content.ReadAsStringAsync();
                        participantList = JsonConvert.DeserializeObject<List<Participant>>(content);
    
                        ParticipantNames();
    
    
                        PickLoading.IsVisible = false;
                        ParticipantPicker.IsVisible = true;
                        Add.IsVisible = true;
                    }
    
                }
    
    
                private void ParticipantNames()
                {
    
                    Items = new ObservableCollection<string>
                    {
    
                    };
                    foreach (var person in participantList)
                    {
                        Items.Add(person.firstname + " " + person.middleinitial + " " + person.lastname + " Age:" +                          
                                ((int.Parse(DateTime.Now.ToString("yyyyMMdd")) -                                                                                                                                                                                 
                                int.Parse(person.dateofbirth.ToString("yyyyMMdd"))) / 10000));
                    }
                    ParticipantPicker.ItemsSource = Items;
                }
    
                public async void LoadAdd()
                {
                    var AddParticipant = new AddPage(lwaid);
                    await Navigation.PushModalAsync(AddParticipant, true);
    
                }
    
                public async void LoadSports()
                {
                    Participant selected = new Participant();
                    var i = ParticipantPicker.SelectedIndex;
                    if (i >= 0)
                    {
                        selected = participantList[i];
    
                        var AvailableSports = new AvailableSports(selected);
                        await Navigation.PushModalAsync(AvailableSports, true);
    
                        ErrorMsg.IsVisible = false;
                        ErrorMsg.Text = "";
                    }
                    else
                    {
                        ErrorMsg.Text = "You must choose a participant...";
                        ErrorMsg.IsVisible = true;
                    }
    
    
                }
    
                protected override void OnAppearing()
                {
                    PickLoading.IsVisible = true;
                    ParticipantPicker.IsVisible = false;
                    Add.IsVisible = false;
                    PopulatePicker();
                }
    
            }
        }
    

Answers

  • kcriswellkcriswell Member ✭✭
    edited May 2018 Accepted Answer

    Got it to work, Here is my code so others can see what i did.

        namespace SportsRegTestApp
        {
            [XamlCompilation(XamlCompilationOptions.Compile)]
            public partial class SelectParticipant : ContentPage
            {
                public string uri = "...";
                List<Participant> participantList = new List<Participant>();
                HttpResponseMessage response = new HttpResponseMessage();
                private ActivityIndicator _activityIndicator = new ActivityIndicator();
                HttpClient client = new HttpClient();
                string lwaid;
                public ObservableCollection<string> Items { get; set; }
    
                public SelectParticipant(string id)
                {
                    InitializeComponent();
    
    
                    lwaid = id;
                    uri += id;
                    while (IsBusy == true)
                    {
                        var indicator = new ActivityIndicator { IsRunning = true };
                    }
    
                }
    
                private async void PopulatePicker()
                {
    
                    response = await client.GetAsync(uri);
                    if (response.IsSuccessStatusCode)
                    {
                        participantList.Clear();
                        var content = await response.Content.ReadAsStringAsync();
                        participantList = JsonConvert.DeserializeObject<List<Participant>>(content);
    
                        ParticipantNames();
    
    
                        PickLoading.IsVisible = false;
                        ParticipantPicker.IsVisible = true;
                        Add.IsVisible = true;
                    }
    
                }
    
    
                private void ParticipantNames()
                {
    
                    Items = new ObservableCollection<string>
                    {
    
                    };
                    foreach (var person in participantList)
                    {
                        Items.Add(person.firstname + " " + person.middleinitial + " " + person.lastname + " Age:" +                          
                                ((int.Parse(DateTime.Now.ToString("yyyyMMdd")) -                                                                                                                                                                                 
                                int.Parse(person.dateofbirth.ToString("yyyyMMdd"))) / 10000));
                    }
                    ParticipantPicker.ItemsSource = Items;
                }
    
                public async void LoadAdd()
                {
                    var AddParticipant = new AddPage(lwaid);
                    await Navigation.PushModalAsync(AddParticipant, true);
    
                }
    
                public async void LoadSports()
                {
                    Participant selected = new Participant();
                    var i = ParticipantPicker.SelectedIndex;
                    if (i >= 0)
                    {
                        selected = participantList[i];
    
                        var AvailableSports = new AvailableSports(selected);
                        await Navigation.PushModalAsync(AvailableSports, true);
    
                        ErrorMsg.IsVisible = false;
                        ErrorMsg.Text = "";
                    }
                    else
                    {
                        ErrorMsg.Text = "You must choose a participant...";
                        ErrorMsg.IsVisible = true;
                    }
    
    
                }
    
                protected override void OnAppearing()
                {
                    PickLoading.IsVisible = true;
                    ParticipantPicker.IsVisible = false;
                    Add.IsVisible = false;
                    PopulatePicker();
                }
    
            }
        }
    
  • lok1lok1 Member ✭✭

    Hi I have used the code but still not getting,
    Can you please help?

  • lok1lok1 Member ✭✭

    public static string Url = "";
    HttpResponseMessage response = new HttpResponseMessage();

        HttpClient client = new HttpClient();
        List<Gender> participantList = new List<Gender>();
    
        public ObservableCollection<string> Items { get; set; }
    

    PopulatePicker();

    private async void PopulatePicker()
    {

            response = await client.GetAsync(Url);
            if (response.IsSuccessStatusCode)
            {
    
                var content = await response.Content.ReadAsStringAsync();
    
                participantList = JsonConvert.DeserializeObject<List<Gender>>(content);
    
    
    
    
                Items = new ObservableCollection<string>
                {
    
                };
    
                foreach (var gend in participantList)
                {
                    Items.Add(gend.gender);
                }
    
  • kcriswellkcriswell Member ✭✭

    There are a few differences between mine and yours. I clear the list before readding it by using the .clear() method. also, try having the

    ```
    Items = new ObservableCollection
    {

            };
    
            foreach (var gend in participantList)
            {
                Items.Add(gend.gender);
            }
    

    ````
    as a separate function and then adding it to the itemsource. This way all the data is loaded all at once.

  • kcriswellkcriswell Member ✭✭
    edited October 2018

    in VM:
    {

        public class [ViewName]ViewModel : INotifyPropertyChanged
        {
    
            private void OnPropertyChanged(string v)
                {
                  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(v));
                 }
    
            private List<'type' or 'object'> _item4Picker;
    
            public List<'type' or 'object'> Item4Picker
            {
                get => _item4Picker;
                set
                {
                    _item4Picker = value;
                    OnPropertyChanged("Item4Picker");
                }
            }
    
            public [ViewName]ViewModel ()
            {
                GetStateList();
    
            }
    
            public async void GetStateList()
            {
                HttpResponseMessage response = new HttpResponseMessage();
                HttpClient client = new HttpClient();
                public string uri = "...";
    
                response = await client.getAsync(uri);
    
                if (response.IsSuccessStatusCode)
                        {
                    var content = await response.Content.ReadAsStringAsync();
                                Item4Picker = JsonConvert.DeserializeObject<List<Participant>>(content);
    
    
                }
    
            }
        }
    

    }

  • kcriswellkcriswell Member ✭✭
    edited October 2018

    In View:
    {
    <picker Itemsource = {binding Item4Picker} [additional xaml here]/>
    }

    In Code-Behind:
    {

            public MainPage(string id)
            {
                InitializeComponent();
                        this.BindingContext = new  [ViewName]ViewModel();
            }
    
    

    }

    Hope that helps.

Sign In or Register to comment.