I am currently using Xamarin Forms and I am using the post
method which I got from github RESTAPI. My application crashes whenever I try to apply the data to my ListView ItemsSource.
The following is the success callback that is currently executed, and it retrieves the JSON and serialize it and storing it in a list called listData.
public class Home : ContentPage
{
private ListView myListView;
private List<Person> listInfo = new List<Person> { };
RESTAPI rest = new RESTAPI();
Uri address = new Uri("http://localhost:6222/testBackEnd.aspx");
public Home ()
{
Dictionary<String, String> data = new Dictionary<String, String>();
rest.post(address, data, success, null);
Content = new StackLayout {
Children =
{
myListView
}
};
}
public void success(Stream stream)
{
DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<Person>));
listData = (List<Person>)sr.ReadObject(stream);
//myListView.ItemsSource = listData;
}
}
Is it because it is not asynchronous, and if so how can I make this method asynchronous? I did one previously on Windows Phone 8.1 using the following await code, is there a Xamarin Forms equivalent available for it?
async public void success(Stream stream)
{
DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<Person>));
listData = (List<Person>)sr.ReadObject(stream);
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
myListView.ItemsSource = listData;
});
}
you can try with this way:
in this way you manage asynchronously the filling of listView.
I've tried this with a lot of data and the performances are better.
If it is because it is asynchronous, then you should do the UI change (always) in the main thread. To do so:
If this doesn't solve it, then async is not the (only?) problem.