Lazy Load JSON Data in Xamarin.Forms ListView: An Overview
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (203)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (65)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (81)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (897)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (39)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (501)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (381)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (323)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Lazy Load JSON Data in Xamarin.Forms ListView (1)

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 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
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

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed