Just getting started with Xamarin... created a Xamarin Forms cross-platform app.
I am trying to fetch data from a REST API and place the data into a ListView.
I know the API url is correct as I've tested it separately in the browser.
The line of code which causes the exception is the "GetStringAsync()" call:
public async void GetData() {
_url = "http://jsonplaceholder.typicode.com/posts/1";
var content = await _client.GetStringAsync(_url); // <---- HERE
var items = JsonConvert.DeserializeObject<List<Post>>(content);
_posts = new ObservableCollection<Post>(items);
listView.ItemsSource = _posts;
}
public class Post {
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage.Content>
<ListView x:Name="listView">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Title}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
The program shows a message on opening in a label. Then upon clicking a button, I want to retrieve the data and show it on the same page, in the ListView (which contains nothing prior).
Running the program results in the error:
"An unhandled exception occured."
Things I've tried...
I've set the "advanced settings" in the Android project under "properties | android options | advanced". I've tried all combinations for the two settings of "httpclient" and "ssl/tls" implementation, despite my API url not being secure (https - I've tried both ways).
I've removed the GetStringAsync call and hard-coded a json object and it loaded fine into the Listview.
I've wrapped the call in a try/catch and changed the regular call to the method from "GetData();" in the click event method to:
Task.Run(async () => await GetData());
and while the error goes away, nothing happens data-wise either.
- I've Googled the @#$% out of the error and circumstances and cannot seem to find an answer.
Any ideas out there?