I am creating an application that requests a small amount of data from a web server in JSON format, deserializes the data using Json.net and returns a list of the user object. I am debugging an application using an Android phone.
Then a list is created using the created list. It seems that the ui code works with ready-made objects inserted into the list instead of the async method. The asynchronous method crashed the application.
public partial class Membership : ContentPage
{
int increment = 1;
public Membership()
{
var task = GetMembers(increment);
List<Person> people = task.Result;
ListView listView = new ListView
{
ItemsSource = people,
ItemTemplate = new DataTemplate(() =>
{
Label nameLabel = new Label();
Label statusLabel = new Label();
nameLabel.SetBinding(Label.TextProperty, "name");
statusLabel.SetBinding(Label.TextProperty, "status");
return new ViewCell
{
View = new StackLayout
{
Padding = new Thickness(0, 5),
Orientation = StackOrientation.Horizontal,
Children =
{
new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Spacing = 0,
Children =
{
nameLabel,
statusLabel
}
}
}
}
};
})
};
this.Content = new StackLayout
{
Children =
{
header,
listView
}
};
}
And the asynchronous task in question:
async Task<List<Person>> GetMembers(int increment)
{
string jsonString;
using (var client = new HttpClient())
{
var responseString = await client.GetStringAsync("GENERIC URL" + "increment=" + increment.ToString());
jsonString = responseString;
}
List<Person> memberList = JsonConvert.DeserializeObject<List<Person>>(jsonString);
return memberList;
}
Now I tested this code bypassing the async task and creating a list of several predefined People, and it worked just fine.
, task.Result; async, , . .