Xamarin.Forms: JSON Data to a ListView(Android & IOS).

Published Sep 13, 2017Last updated Sep 16, 2017
Xamarin.Forms: JSON Data to a ListView(Android & IOS).

Have you ever imagined developing three apps once on android,IOS and windows once ? Well, follow this simple series and enjoy without having worry about developing each platform app seperatly 😎!

Today we are going to make a simple application with a list of items with offline capability in Xamarin.Forms.

Introduction & Requirements

Xamarin.Forms is an API that enables us to quickly build native apps for iOS, Android, and Windows completely in C#. Here are the requirements before we dig in:

  1. Mac System Requirements
    You can use Visual Studio in Mac to develop Xamarin.Forms apps on OS X El Capitan (10.11) or any other newer versions. To develop iOS apps, I recomended at least having the iOS 10 SDK and Xcode 8 installed.
    Note that Windows apps cannot be developed on macOS.

  2. Windows System Requirements.
    Xamarin.Forms apps for iOS and Android can be built on any Windows installation that supports Xamarin development. This requires Visual Studio 2013 Update 2 or newer versions running on Windows 7 or higher. A networked Mac is required for iOS development.

There are some additional requirements for the following types of Windows apps:

  1. Universal Windows Platform (UWP):

    • Windows 10
    • Visual Studio 2015 or newer
    • Universal Windows Developer Tools

    UWP projects are included in Xamarin.Forms solutions created in Visual Studio 2015 and Visual Studio 2017. You can also add a Universal Windows Platform (UWP) App to an existing Xamarin.Forms solution.

  2. Windows 8.1 and Windows Phone 8.1 WinRT:

    • Windows 8.1
    • Visual Studio 2013 Update 2 or newer.

After meeting all these requirements, it’s time to get our hands dirty! I will be using Visual Studio 2017.

Let’s dive into the code!

STEP 1:

Go to File > New > Project > Cross Platform > Cross Platform App (Xamarin.Forms or Native).

1_image.png

Then check Xamrin.Forms and Shared Project and click Ok.

STEP2:

Install the following Nuget Packages .

In order to install them, right click on Project > Manage Nuget Packages for the solution > Browse):

  1. Newtonsoft.Json
  2. SQLite.Net.Async-PCL
  3. SQLite.Net.Core-PCL
  4. Xam.Plugin.Connectivity.
  5. Microsoft.Net.Http

STEP 3:

This is the URL which contains the JSON data. Click it to view the data.

Now if you notice the data has 5 objects namely :
i).image.
ii).title.
iii).artist.
iv).thumbnail_image
v).url

So with the Help of json2csharp site, it can help you to generate C# code out of JSON to create an Object/Model Class.
use this link to it

Now we have to create our Object/Model Class. Let’s call it Items.cs
:

using System;
using System.Collections.Generic;
using System.Text;

namespace MySimpleList
{
    class Items
    {
        
        public string image { get; set; }
        public string title { get; set; }
        public string artist { get; set; }
        public string thumbnail_image { get; set; }
        public string url { get; set; }
    }
}


STEP 4 :

Now since we are going to make an Internet/ Http Request we need to provide permissions in our project.

In android:
We need to go the MySimpleList.Android and we navigate to Properties>AndroidManifest.xml and you add this internet permission.

<uses-permission android:name="android.permission.INTERNET" />.

In IOS:
You go to MySimpleList.IOS then info.plist and add the following in the source code.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key><true/>
</dict>

for more information you can visit this page and research more .

STEP 5

Here we are going to ask for an Http Request which will come with JSON data, after that then we deserialize the data and we attach or bind the data to our ListView. Here in Xamarin.Forms no need of sweating too much, this action is done in few steps.

Below is the MainPage.xaml.cs class

using Newtonsoft.Json;
using Plugin.Connectivity;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace MySimpleList
{
  public partial class MainPage : ContentPage
  {

        public int Count = 0;
        public short Counter = 0;
        public int SlidePosition = 0;
        string heightList;
        int heightRowsList = 90;
        private const string Url = "http://rallycoding.herokuapp.com/api/music_albums";
        // This handles the Web data request
        private HttpClient _client = new HttpClient();
        public MainPage()
    {
      InitializeComponent();
            // We call the OnGetList from Here 
            OnGetList();
    }


        protected async void OnGetList()
        {
            if (CrossConnectivity.Current.IsConnected)
            {

                try
                {
                    //Activity indicator visibility on
                    activity_indicator.IsRunning = true;
                    //Getting JSON data from the Web
                    var content = await _client.GetStringAsync(Url);
                    //We deserialize the JSON data from this line
                    var tr = JsonConvert.DeserializeObject<List<Items>>(content);
                    //After deserializing , we store our data in the List called ObservableCollection
                    ObservableCollection<Items> trends = new ObservableCollection<Items>(tr);

                    //Then finally we attach the List to the ListView. Seems Simple :)
                    myList.ItemsSource = trends;

              
                    //We check the number of Items in the Observable Collection
                    int i = trends.Count;
                    if (i > 0)
                    {
                        //If they are greater than Zero we stop the activity indicator
                        activity_indicator.IsRunning = false;
                    }

                    //Here we Wrap  the size of the ListView according to the number of Items which have been retrieved 
                    i = (trends.Count * heightRowsList);
                    activity_indicator.HeightRequest = i;

                }
                catch (Exception ey)
                {
                    Debug.WriteLine("" + ey);
                }

            }

        }

    }
}

STEP 6:

Open MainPage.xml and to Edit it.

Now, in order to make a list of items, we need a ListView and an activity indicator which shows that data is loading in the ListView.

Let's put this in our code:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MySimpleList"
             x:Class="MySimpleList.MainPage">


    <!-- Activity Indicator-->
    <ActivityIndicator VerticalOptions="Center" HorizontalOptions="Center" x:Name="activity_indicator" Color="#4D7EE1" />
    <!-- ListView-->
    <ListView x:Name="myList" HasUnevenRows="true">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <!-- Here we make a Horizontal orientation with the help of StackLayout-->
                    <StackLayout Orientation="Horizontal" Margin="5" HeightRequest="90">
                        <Image Source="{Binding image}" WidthRequest="100" HeightRequest="200" Aspect="AspectFit" />
                        <StackLayout VerticalOptions="Center">
                            <Label Text="{Binding title}" TextColor="#1C5AD8" />
                        </StackLayout>
                        <Image HorizontalOptions="EndAndExpand" HeightRequest="20" WidthRequest="20" Source="more_icon.png" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</ContentPage>

If you look closely at the code above, it may look a bit weird. Don't worry, let's go through the explanation step-by-step!

I have inserted a ListView, and inside it, I attempted to bind it with data. All you have to know is that if you want a customized binded list in Xamarin.forms, you have to include the following in the ListView:

<ListView.ItemTemplate>,<DataTemplate>,<ViewCell>

It should be clearer to you that I have binded a "Label" with an "Image" instead the StackLayout in my code. This provides a horizontal orienatation. With that said, the "Image" has another stackLayout which gives it a vertical orientation, which will style our list nicely.

So that's how you can make a simple List Application on both IOS, Windows and Android.

Hope this post was clear! Feel free to leave a comment if you have any questions!

Discover and read more posts from Lutaaya Huzaifah Idris
get started
Enjoy this post?

Leave a like and comment for Lutaaya

Be the first to share your opinion

Get curated posts in your inbox

Read more posts to become a better developer