0

I'm a beginner with C# and whole .NET (just wanted to mention at the beginning). So I'm learning Xamarin and APIs.

I've got the problem with fetching some data from API (https://jsonplaceholder.typicode.com/posts) to display inside the app. Once I execute the app, it gives me an error:

System.InvalidCastException: 'Specified cast is not valid'.

I also don't see where is it failing (after error, exception window is blank - like not showing where it stops).

using ExerciseApp.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using Xamarin.Forms;

namespace ExerciseApp
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            GetPosts();
        }

        private async void GetPosts()
        {
            HttpClient client = new HttpClient();
            var response = await client.GetStringAsync("https://jsonplaceholder.typicode.com/posts");
            var posts = JsonConvert.DeserializeObject<List<Posts>>(response);

            PostsListView.ItemsSource = posts;
        }
    }
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ExerciseApp.MainPage">

    <StackLayout BackgroundColor="White">
        <Frame BackgroundColor="#581845" Padding="10" CornerRadius="5" Margin="25">
            <Label Text="ʕ•ᴥ•ʔ" HorizontalTextAlignment="Center" TextColor="White" FontSize="30"/>
        </Frame>
        <Label Text="Welcome to Exercise app with RESTAPI and NHibernate" TextColor="#581845" FontSize="Title" Padding="10" HorizontalTextAlignment="Center"/>
        <Label FontSize="20" Padding="20" HorizontalTextAlignment="Center" TextColor="#581845">
            <Label.FormattedText>
                <FormattedString>
                    <FormattedString.Spans>
                        <Span Text="Here we will load some data"/>
                    </FormattedString.Spans>
                </FormattedString>
            </Label.FormattedText>
        </Label>
        <ListView x:Name="PostsListView">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackLayout Orientation="Horizontal">
                        <Label Text="{Binding id}" TextColor="#581845"></Label>
                        <Label Text="{Binding title}" TextColor="#581845"></Label>
                    </StackLayout>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>
namespace ExerciseApp.Models
{
    public class Posts
    {
        public int userId { get; set; }
        public int id { get; set; }
        public string title { get; set; }
        public string body { get; set; }
    }
}

4
  • if the exception doesn't show you where it occurs, check the stack trace, and if that doesn't help then you need to set a breakpoint in the debugger and step through each line of code until you hit the exception Commented Mar 21, 2021 at 16:18
  • @Jason I went through all the breakpoints now - It didn't stop at certain point. It just showed after executing everything (so after function). I think this is why it's not showing any info in error handler. Commented Mar 21, 2021 at 16:24
  • GetPosts is async, so try calling it from OnAppearing using await instead of the constructor Commented Mar 21, 2021 at 16:35
  • @Jason sorry but I'm quite new into it and I have no idea how to do it. Commented Mar 21, 2021 at 16:41

1 Answer 1

1

ListView must use a Cell type in their template. Adding a ViewCell into your XAML will fix this problem

    <ListView x:Name="PostsListView">
        <ListView.ItemTemplate>
            <DataTemplate>
              <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Label Text="{Binding id}" TextColor="#581845"></Label>
                    <Label Text="{Binding title}" TextColor="#581845"></Label>
                </StackLayout>
              </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView> 

alternately, you can use a CollectionView which allows you to create templates without the restriction of using a Cell

Sign up to request clarification or add additional context in comments.

1 Comment

And You are the boss! Works like a charm. Thank You very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.