Farshad Momtaz
Farshad Momtaz

Reputation: 424

Xamarin forms page doesn't load until async call is done

I'm trying to open a new page which shows a list that is populated with data from the server. The call to get the data from the server is done using an async function that is called from OnAppearing method. However, even though the method is async, my UI page is not shown until the call is done. How can I fix that or what is the best practice to make this call?

This is my XAML code for the page:

<StackLayout>
  <Label
    x:Name="NoPostsMessage"
    Text="You have not created any posts yet :("
    VerticalOptions="CenterAndExpand"
    HorizontalOptions="CenterAndExpand" />

  <ListView
    x:Name="PostList"
    SelectionMode="None">
    <ListView.ItemTemplate>
      <DataTemplate>
        <TextCell Text="{Binding Text}" Detail="{Binding Detail}" />
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</StackLayout>

This is my C# code:

protected override void OnAppearing()
{
  base.OnAppearing();

  GetContributions();
}

async private void GetContributions()
{
  HttpClient client = new HttpClient();

  client.DefaultRequestHeaders.Add("Accept", "application/json");

  HttpResponseMessage response = await client
    .GetAsync
    (
      "websiteURL.com"
    );

  if (response.IsSuccessStatusCode)
  {
    APIResponse data = JsonConvert.DeserializeObject<APIResponse>(response.Content.ReadAsStringAsync().Result);
    if (data.ResponseCode == 1)
    {
      string payloadData = data.Data.ToString();
      List<TextCell> userPosts = JsonConvert.DeserializeObject<List<TextCell>>(payloadData);

      if (userPosts.Count == 0)
      {
        NoPostsMessage.IsVisible = true;
        PostList.IsVisible = false;
      }
      else
      {
        NoPostsMessage.IsVisible = false;
        PostList.IsVisible = true;

        ReportsList.ItemsSource = userPosts;
      }
    }
    else
    {
      await DisplayAlert("Error", data.ErrorMessage, "OK");
    }
  }
  else
  {
    await DisplayAlert("Error", "An error has occurred, please try again later", "OK");
  }
}

Upvotes: 2

Views: 1801

Answers (1)

Jason
Jason

Reputation: 89102

if you do not use await, the async call will block the UI

protected async override void OnAppearing()
{
  base.OnAppearing();

  await GetContributions();
}

Upvotes: 4

Related Questions