Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (158).NET Core  (28).NET MAUI  (50)Angular  (67)ASP.NET  (50)ASP.NET Core  (78)ASP.NET MVC  (88)Azure  (32)Blazor  (144)DocIO  (23)Essential JS 2  (80)Essential Studio  (171)File Formats  (28)Flutter  (121)JavaScript  (179)Microsoft  (112)PDF  (67)React  (55)Succinctly series  (126)Syncfusion  (582)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (36)Webinar  (32)Windows Forms  (58)WinUI  (45)WPF  (135)Xamarin  (153)XlsIO  (25)Other CategoriesBarcode  (5)BI  (29)Bold BI  (4)Build conference  (6)Business intelligence  (53)Button  (4)C#  (118)Chart  (56)Cloud  (11)Company  (445)Dashboard  (7)Data Science  (3)Data Validation  (6)DataGrid  (54)Development  (372)Doc  (7)DockingManager  (1)eBook  (95)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (23)Extensions  (17)File Manager  (4)Gantt  (11)Gauge  (9)Git  (4)Grid  (27)HTML  (10)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (298)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (29)Performance  (9)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (7)Road Map  (10)Scheduler  (36)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (22)Solution Services  (2)Spreadsheet  (11)SQL  (8)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (91)UI  (209)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (23)Visual Studio Code  (14)Web  (341)What's new  (194)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
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:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top