Today, we will discuss how to show data in ListView with API using
Xamarin forms in different platforms.
Let’s start.
Step 1:
Open Visual studio and create an Application. Select new project, then cross-platforms, Blank App (Xamarin.Forms Portable) and enter project name (as figure 1).
Press OK Button as in the following figure 1.
Figure 1
Once you press OK, you can see 6 more projects loaded in Solution like TestApp (Portable), TestApp.Droid, TestApp.iOS, TestApp.UWP, TestApp.Windows, TestApp.WinPhone.
Step 2:
Now we will create a new Xaml page for getting data in listview. So Select TestApp (Portable) project -> right click -> select Add -> Select New item as shown in figure 2.
Figure 2.
When you click a new item then dialog opens, select Cross-platform, then Forms Xaml Page and mention name GetdatainList. After that click Add button as in the following figure 3.
Figure 3
Step 3:
Now open GetdatainList.xaml page and write the following code,
- <StackLayout BackgroundColor="White">
- <ListView x:Name="ListView1" RowHeight="60">
- <ListView.ItemTemplate>
- <DataTemplate>
- <ViewCell>
- <StackLayout Orientation="Vertical" Padding="8,0,8,0">
- <Label Text="{Binding ArticleTitle}" TextColor="#000" FontSize="14" LineBreakMode="TailTruncation" />
- <Label Text="{Binding description}" TextColor="#000" LineBreakMode="TailTruncation" />
- </StackLayout>
- </ViewCell>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- </StackLayout>
After that opens GetdatainList.xaml.cs page and write the following code; create one class for accessing properties and create one method for binding the data with API.
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using Xamarin.Forms;
- namespace Testapp
- {
- public partial class GetDatainList : ContentPage
- {
- public class ItemClass
- {
- public string ArticleTitle { get; set; }
- public string description { get; set; }
- }
- public GetDatainList()
- {
- InitializeComponent();
- LoadData();
- }
- public async void LoadData()
- {
- var content = "";
- HttpClient client = new HttpClient();
- var RestURL = your api url.
- client.BaseAddress = new Uri(RestURL);
- client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
- HttpResponseMessage response = await client.GetAsync(RestURL);
- content = await response.Content.ReadAsStringAsync();
- var Items = JsonConvert.DeserializeObject<List<ItemClass>>(content);
- ListView1.ItemsSource = Items;
- }
- }
- }
Step 4:
Finally build your project when build is successful and then run project. Now you can see result in different platforms as in the following figure 4.
Figure 4
Summary
Today, we discussed how to show data in ListView with API using Xamarin forms. I hope you enjoyed this article.