AboutContact

Windows phone ListView tutorial: how to load data from JSON

You'll learn how to define a custom windows phone listview using C# in Visual Studio Express. You'll learn how to load data from url using the JSON format in an asynchronous way, how to define the xaml for a custom ListView and display the elements.

This is the example Windows Phone ListView that you'll obtain:

 

Let's create a new Windows Phone 8.1 blank app using the C# language .

Layout Definition: Windows phone ListView

Let's now define the app layout. Double click on the MainPage.xaml file. This will open the layout editor for the main page. Click on the toolbox menu and add a ListView element.

We'll now configure the ListView cell, by adding two textblocks elements. On the code, on the right view, add this code:

<Page
    ...
    Background="white">

    <Grid>
        <ListView x:Name="list" Margin="5,5">
            <ListView.Resources>

                <DataTemplate x:Key="myCell">
                    <Border BorderBrush="Black"  BorderThickness="0,0,0,1" >
                        <Grid Margin="5" >
                            <TextBlock x:Name="country" Margin="0,0,80,0" TextWrapping="Wrap"  Text="{Binding country}" Width="auto" FontSize="20"  Foreground="Black"/>
                            <TextBlock x:Name="code" FontSize="20" HorizontalAlignment="Right"  Foreground="Black"  Text="{Binding code}" />
                        </Grid>                        
                    </Border>
                </DataTemplate>
               
            </ListView.Resources>

            <ListView.ItemContainerStyle>
                <Style TargetType="ListViewItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                </Style>
            </ListView.ItemContainerStyle>

            <ListView.ItemTemplate>
                <StaticResource ResourceKey="myCell"/>
            </ListView.ItemTemplate>

        </ListView>

    </Grid>

</Page>

This code allows you to have a full width List view cell, a textblock element on the right and one on the left. The textblock on the left has a right-margin of 80  (0,0,80,0) , in order to leave the space to the right element. The elements are filled using the windows phone Binding feature.

Define the download json data function

Let's start now the coding part. Create a new class by going to project - add Class. Call it download_data and add it.

This class has the goal to download the data in an asynchronous way and as soon as the data are arrived, to call the main class with the data.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;

namespace listview_from_json_tutorial
{

    public class DownloadCompleteData : EventArgs
    {
        public String data{ get; set; }
    }

    class download_data
    {

        public event EventHandler<DownloadCompleteData> downloadDatacomplete;

        public void get_data(String url)
        {
            DownloadDataAsync(url);
        }


        async void DownloadDataAsync(String url)
        {
            HttpClient client = new HttpClient();
            Task<string> getStringTask = client.GetStringAsync(url);
            string urlContents = await getStringTask;

            DownloadCompleteData data_to_send = new DownloadCompleteData();
            data_to_send.data = urlContents;

            DownloadDataCompleteEvent(data_to_send);

        }

        protected virtual void DownloadDataCompleteEvent(DownloadCompleteData e)
        {
            EventHandler<DownloadCompleteData> handler = downloadDatacomplete;
            if (handler != null)
            {
                handler(this, e);
            }
        }


    }
}

As soon as the data are arrived, the DownloadDataCompleteEvent function is called. This function has the goal to call the main class with the defined handler. We will see this step in a few.

Extract the data from json

Let's define now the Main Class. As a first thing import the JSON package. This is a free library that allows you to do the JSON data extraction very easily. Click on Project, manage nuget packets, click on online section, search for the JSON.NET package and install it.

 

Expand the MainPage.xaml and double click on MainPage.xaml.cs.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


namespace listview_from_json_tutorial
{

    public sealed partial class MainPage : Page
    {

        public class DataList
        {
            public string country { get; set; }
            public string code { get; set; }
        }


        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;

            Loaded += new RoutedEventHandler(Page_Loaded);
        }


        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            download_data dwl = new download_data();

            dwl.downloadDatacomplete += data_arrived;
            dwl.get_data("https://www.kaleidosblog.com/tutorial/tutorial.json");
        }


        void data_arrived(object sender, DownloadCompleteData e)
        {

            String data = e.data;

            JArray obj = JArray.Parse(data);

            for (int i = 0; i < obj.Count; i++)
            {

                JObject row = JObject.Parse(obj[i].ToString());

                var item = new DataList();
                item.country = row["country"].ToString();
                item.code = row["code"].ToString();

                list.Items.Add(item);
            }


        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }
    }
}

This code implements the data_arrived function that is called from the download_data class as soon as the data are arrived. Here the JSON extraction is done. The Main Page class defines also the DataList struct. This class defines the country and codes variables that are binded to the ListView.

Download this example.

Leave a comment








Comments


- 31 March 2016 at 12:56
data is not populated in listview control how it resolved please provide assistance?
Andrea - 02 April 2016 at 20:59
Hi, can you please send me your project to let me help you?
- 15 December 2015 at 08:17
Hello You have done the parsing for jsonarray could u plzz provide an example for jsonobject
Aman - 15 December 2015 at 08:40
with the same example
Andrea - 15 December 2015 at 21:02
Hi, thank you for your comment. In the example I've used jsonobjects too, they are the country and the code. What for an extra example do you need? Tell me the data structure you need
Aman Tiwari - 17 December 2015 at 13:01
I am unable to bind my json data in the listview the json data is displaying in debug window but its not able to bind in the list view
Aman Tiwari - 17 December 2015 at 13:18
Using this example could u plzz tell me what should i do
Aman Tiwari - 17 December 2015 at 13:18
Using this example could u plzz tell me what should i do
- 31 August 2015 at 19:37
Where is list from? list.Items.Add(item); I cannot see it anywhere else.
Andrea - 31 August 2015 at 20:09
Hi, the list is declared in the xaml file. (MainPage.xaml). There is the ListView, (ListView x:Name="list") with the corresponding variable name (list in this case - you can call it in the source code). Hope it helps! :-)
Andressa - 10 September 2015 at 21:50
I got it.Thank you!





AboutContactPrivacy