How do I display REST data from an api in a simple list?

I am trying to pull all the names of teams and place them in a simple list. I have tried so doing this

private void ParseAndDisplay(JsonValue json)
{
dynamic teamData = json["teams"];

        //TextView name = FindViewById<TextView>(Resource.Id.txtName);
        string[] teams;
        foreach (var team in teamData)
        {
            var name = team["name"];
            Console.Out.WriteLine("\r\n {0}", name);
            teams = new string[] { name };
            //TextView name = FindViewById<TextView>(Resource.Id.txtName);
            //name.Text = team["name"];
            ListAdapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItem1, teams);
        }

However on my device it only displays the name of the last team in the data whereas in the output it shows all of them.

Tagged:

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    I don't know Xamarin.Android, but I think the problem is that you declare each time you loop in the foreach the "teams" variable.

    I think you should start from something like

        string[] teams = new string[teamData.Count()]; // or teamData.GetLengt()... I don't know what is teamData...
    int ii = 0;
        foreach (var team in teamData)
        {
            var name = team["name"];
            Console.Out.WriteLine("\r\n {0}", name);
            teams[ii++] = name; // = new string[] { name };
            //TextView name = FindViewById<TextView>(Resource.Id.txtName);
            //name.Text = team["name"];
        }
    
            ListAdapter = new ArrayAdapter<String>(this, Android.Resource.Layout.SimpleListItem1, teams);
    

    (I don't know if it works, but I think it is more correct than your version)

Sign In or Register to comment.