Copied RSS Feed

Xamarin

Lazy Load JSON Data in Xamarin.Forms ListView: An Overview

Lazy loading, or on-demand loading, is a technique that enhances loading performance. With it, we can show a fixed amount of data in the initial loading of a huge data set. Once the user has scrolled to the end of that data, we can add more to the end of the list until the data ends. It is also known as infinite scrolling or incremental loading.

The Syncfusion Xamarin.Forms ListView (SfListView) control is a list-like interface. It can render a set of data items vertically or horizontally in a linear or grid structure. It also provides lazy loading support with a Load More feature. You can enable lazy loading both manually and automatically.

This blog teaches you how to show a fixed amount of JSON data on initial loading (lazy load) and show a busy indicator while loading the remaining data on scrolling in the Xamarin.Forms ListView.

Populate JSON data collection from a URI

Follow these steps to populate a JSON data collection from a URI:

Step 1: Install the Newtonsoft.Json NuGet package to your Xamarin.Forms shared project.

Step 2: Then, download the JSON data from your URI using the HttpClient method and store it in the local file.

public async Task<bool> DownloadJsonAsync()
{
  try
  {
    var url = "https://ej2services.syncfusion.com/production/web-services/api/Orders"; //Set your REST API url here
 
    //Sends a request to retrieve data from the web service for the specified Uri
    var response = await httpClient.GetAsync(url);
    using (var stream = await response.Content.ReadAsStreamAsync()) //Reads data as stream
    {
      //Gets the path to the specified folder
      var localFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
 
      var newpath = Path.Combine(localFolder, "Data.json"); // Combine path with the file name
 
      var fileInfo = new FileInfo(newpath);
      File.WriteAllText(newpath, String.Empty);
 
      //Creates a write-only file stream
      using (var fileStream = fileInfo.OpenWrite())
      {
         await stream.CopyToAsync(fileStream); //Reads data from the current stream and write to destination stream (fileStream)
      }
    }
  }
  catch (OperationCanceledException e)
  {
     System.Diagnostics.Debug.WriteLine(@"ERROR {0}", e.Message);
     return false;
  }
  catch (Exception e)
  {
     System.Diagnostics.Debug.WriteLine(@"ERROR {0}", e.Message);
     return false;
  }
  return true;
}

Step 3: Now you can get the JSON data as a list of dynamic objects. Refer to the following code example.

private async void GetDataAsync()
{
  isDownloaded = await DataService.DownloadJsonAsync();
  if (isDownloaded)
  {
    var localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
    var fileText = File.ReadAllText(Path.Combine(localFolder, "Data.json"));
 
    //Read data from the local path and set it to the collection bound to the ListView.
    JSONCollection = JsonConvert.DeserializeObject<IList<dynamic>>(fileText);
    totalItems = JSONCollection.Count;
  }
}

The LoadMoreCommand property gradually uses the JSON data collection to load the items on demand. As I said before, we can lazy load the data either manually or automatically in the Xamarin.Forms ListView.

Let’s see how to achieve this with code examples!

Lazy loading JSON data manually in Xamarin.Forms ListView

To load more items manually in the ListView, set the LoadMoreOption as Manual using the LoadMoreCommand and LoadMoreCommandParameter properties. Doing this will load more items on tapping the Load More button at the end of the list.

Refer to the following code example to bind the ViewModel.LoadMoreItemsCommand to the Xamarin.Forms ListView.

<syncfusion:SfListView x:Name="listView"
                         ItemSize="{OnPlatform Android=115, Default=100}"
                         ItemsSource="{Binding Items}"
                         LoadMoreOption="Auto"
                         LoadMoreCommand="{Binding LoadMoreItemsCommand}"
                         IsBusy="{Binding IsBusy}"
                         ItemSpacing="5"
                         LoadMoreCommandParameter="{Binding Source={x:Reference Name=listView}}">

Refer to the following code definition for LoadMoreItemsCommand in the ViewModel.

private bool CanLoadMoreItems(object obj)
{
  if (Items.Count >= totalItems)
  return false;
  return true;
}
 
private async void LoadMoreItems(object obj)
{
   var listview = obj as SfListView;
   try
   {
      IsBusy = true;
      await Task.Delay(1000);
      var index = Items.Count;
      var count = index + 3 >= totalItems ? totalItems - index : 3;
      AddProducts(index, count);
   }
   catch
   {
 
   }
   finally
   {
      IsBusy = false;
   }
}
 
private void AddProducts(int index, int count)
{
  for (int i = index; i < index + count; i++)
  {
     Items.Add(JSONCollection[i]);
  }
}

After executing the above code example, we will get the output like in the following GIF image.

Lazy Loading JSON Data in Xamarin.Forms ListView Manually with a Load More Button

Lazy loading JSON data automatically in Xamarin.Forms ListView

To load more items automatically in the ListView, set the LoadMoreOption as Auto using the LoadMoreCommand and LoadMoreCommandParameter properties. This will load more items when the scrollbar reaches the end of the list.

Refer to the following code example.

<syncfusion:SfListView x:Name="listView"
                         ItemSize="{OnPlatform Android=105, Default=100}"
                         ItemsSource="{Binding Items}"
                         LoadMoreOption="Auto"
                         LoadMoreCommand="{Binding LoadMoreItemsCommand}"
                         IsBusy="{Binding IsBusy}"
                         ScrollBarVisibility="Always"
                         LoadMoreCommandParameter="{Binding Source={x:Reference Name=listView}}"/>

After executing the above code example, we will get the output like in the following GIF image.

Lazy Loading JSON Data in Xamarin.Forms ListView Automatically

GitHub reference

Refer to the complete example for lazy loading JSON data in Xamarin.Forms ListView on GitHub.

Conclusion

Thanks for reading! We have seen how to lazy load JSON data in the Syncfusion Xamarin.Forms ListView. For more details, refer to the load more feature in Xamarin ListView documentation. Try out the steps in this blog and easily enhance your loading performance. Don’t forget to leave your feedback in the comments section below!

For current customers, the new Essential Studio version is available for download from the License and Downloads page. If you are not yet a Syncfusion customer, you can try our 30-day free trial to check out our newest features.

You can also contact us through our support forumsupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Meet the Author

Jayaleshwari N

Jayaleshwari N works for Syncfusion as a product manager. She has been a .NET developer since 2013, and has experience in the development of custom controls in Xamarin and MAUI platforms.