Load more items without button click

SreeeeSreeee INMember ✭✭✭✭✭

Dears,

I am implementing load more items to listview without a button.

My code:

 public partial class DashBoardPage : ContentPage
  {
    ObservableCollection<string> Items;
    bool isLoading;

    public DashBoardPage()
    {
        InitializeComponent();

        Items = new ObservableCollection<string>();
        var listview = new ListView();

        listview.ItemsSource = Items;
        listview.ItemAppearing += (sender, e) =>
        {
            if (isLoading || Items.Count == 0)
                return;

            //hit bottom!
            if (e.Item.ToString() == Items[Items.Count - 1])
            {
                LoadItems();
            }
        };
        LoadItems();
    }

    public async void LoadItems()
    {
        isLoading = true;
        HttpClient client = new HttpClient();
        var response = await client.GetAsync("My Url");
        string tweetJson = await response.Content.ReadAsStringAsync();

        UserTweetResponse userTweetResponse = new UserTweetResponse();
        if (tweetJson != "")
        {
            userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
        }
        ListView1.ItemsSource = userTweetResponse.userTweetsList;
        isLoading = false;
    }
}

I refer the following link and confused with the for loop inside LoadItems():
https://montemagno.com/load-more-items-at-end-of-listview-in/
for (int i = 0; i < 20; i++)
{
Items.Add (string.Format("Item {0}", Items.Count));
}
In my case I am using itemSource property to bind the response to list view.
How can I fix this?
Thanks in advance :)

Tagged:

Best Answers

  • CharwakaCharwaka IN ✭✭✭✭✭
    Accepted Answer

    Hi @Sreeee

    paste this whole , it will work

    using System;
    using System.Diagnostics;
    using System.Net.Http;
    using Newtonsoft.Json;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    using System.Collections.ObjectModel;
    using System.Threading.Tasks;
    
    namespace SmartTweet
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class DashBoardPage : ContentPage
        {
            int i = 1;
            bool loadMore;
            ObservableCollection<UserTweetsList> Items =new ObservableCollection<SmartTweet.UserTweetsList>();
            bool isLoading;
            UserTweetResponse userTweetResponse;
            public DashBoardPage()
            {
                InitializeComponent();
    
    
    
                ListView1.ItemAppearing += (sender, e) =>
                {
                    if (isLoading || Items!=null &&  Items.Count == 0)
                        return;
    
                    //hit bottom
                    if (userTweetResponse.userTweetsList!=null && userTweetResponse.userTweetsList.Count>0)
                    {
                        UserTweetsList item = userTweetResponse.userTweetsList[userTweetResponse.userTweetsList.Count - 1];
                        if ((e.Item as UserTweetsList).tweetId.ToString() == item.tweetId.ToString())
                        {
                            Debug.WriteLine("Enter bottom");
                            loadMore = true;
                            UserTweetsList();
    
                        }
                    }
    
    
                };
    
            }
            protected async override void OnAppearing()
            {
                await UserTweetsList();
    
    
                base.OnAppearing();
            }
            async void ButtonClicked(Object sender, EventArgs e)
            {
                loadMore = true;
               // await UserTweetsList();
            }
    
            public async Task UserTweetsList()
            {
                isLoading = true;
                if (loadMore)
                {
                    i = i + 1;
                }
                int countInInt = i * 3;
                try
                {
                    string applicationId = "1";
                    string siteId = "5";
                    string userId = "225";
                    string ownedBy = "me";
                    string period = "before";
                    string count = countInInt.ToString();
    
                    DateTime dt = DateTime.Now.ToLocalTime();
                    string date = dt.Year.ToString() + "-" + dt.Month.ToString() + "-" + dt.Day.ToString() + " " + dt.Hour.ToString() + ":" + dt.Minute.ToString() + ":" + dt.Second.ToString() + "." + dt.Millisecond.ToString();
    
                    HttpClient client = new HttpClient();
                    var response = await client.GetAsync("http://54.208.96.132:8090/smartwcm-admin/rest/v3/tweet/usertweetshb/applicationid/" + applicationId + "/siteid/" + siteId + "/userid/" + userId + "/ownedby/" + ownedBy + "/date/" + date + "/period/" + period + "/count/" + count + "?swcmTicket=69f2ed48-6850-4e0f-a2e9-90b54c50fd28");
                    string tweetJson = await response.Content.ReadAsStringAsync();
                    Debug.WriteLine("tweetList:>" + tweetJson);
    
                     userTweetResponse = new UserTweetResponse();
                    if (tweetJson != "")
                    {
                        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
                        foreach (var tweet in userTweetResponse.userTweetsList)
                        {
                            if (!Items.Contains(tweet))
                            {
                                Items.Add(tweet);
                            }
    
                            //Items.Add(tweet.ToString());
                        }
                    }
                    ListView1.ItemsSource = userTweetResponse.userTweetsList;
                    isLoading = false;
                    if (userTweetResponse.userTweetsList.Count == 0)
                    {
                        //loadMoreButton.IsVisible = false;
                        blue_holo_circle.IsVisible = false;
                        blueLine.IsVisible = false;
                    }
                    else
                    {
                        //loadMoreButton.IsVisible = true;
                        blue_holo_circle.IsVisible = true;
                        blueLine.IsVisible = true;
                    }
    
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
                }
            }
        }
    }
    

Answers

  • SelvamzSelvamz INMember ✭✭

    @Sreeee , You can try Syncfusion SfListView which has support to load more items automatically when end of list reached by default.
    https://help.syncfusion.com/xamarin/sflistview/loadmore
     
    You can check out the samples from android store and iTunes.
    https://play.google.com/store/apps/details?id=com.syncfusion.samplebrowser
    https://itunes.apple.com/us/app/syncfusion-controls-explorer/id1109963411?mt=8"
     
    Refer: ListView -> Load More sample for your requirement.

     
    Syncfusion controls is available for free through the community license program if you qualify (less than 1 million USD in revenue).
    Note: I work for Syncfusion.

  • SreeeeSreeee INMember ✭✭✭✭✭

    @Selvamz said:
    @Sreeee , You can try Syncfusion SfListView which has support to load more items automatically when end of list reached by default.
    https://help.syncfusion.com/xamarin/sflistview/loadmore
     
    You can check out the samples from android store and iTunes.
    https://play.google.com/store/apps/details?id=com.syncfusion.samplebrowser
    https://itunes.apple.com/us/app/syncfusion-controls-explorer/id1109963411?mt=8"
     
    Refer: ListView -> Load More sample for your requirement.

     
    Syncfusion controls is available for free through the community license program if you qualify (less than 1 million USD in revenue).
    Note: I work for Syncfusion.

    Thanks for your response.
    I need to implement this using itemAppearing(), do you have any suggestion for that?

  • CharwakaCharwaka INMember ✭✭✭✭✭

    Hi @Sreeee

    DM me a URL

  • SreeeeSreeee INMember ✭✭✭✭✭

    @Charwaka said:
    Hi @Sreeee

    DM me a URL

    What? Which url? I didn't get you...

  • CharwakaCharwaka INMember ✭✭✭✭✭

    @Sreeee said:

    @Charwaka said:
    Hi @Sreeee

    DM me a URL

    What? Which url? I didn't get you...

    var response = await client.GetAsync("My Url");

  • SreeeeSreeee INMember ✭✭✭✭✭

    @Charwaka said:

    @Sreeee said:

    @Charwaka said:
    Hi @Sreeee

    DM me a URL

    What? Which url? I didn't get you...

    var response = await client.GetAsync("My Url");

    Which is the url from I got the Json data

  • SreeeeSreeee INMember ✭✭✭✭✭

    Inside of LoadItems(), I add the code for Items using foreach:

    public async void LoadItems()
       {
        isLoading = true;
        HttpClient client = new HttpClient();
        var response = await client.GetAsync("My Url");
        string tweetJson = await response.Content.ReadAsStringAsync();
    
    UserTweetResponse userTweetResponse = new UserTweetResponse();
    if (tweetJson != "")
    {
        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
        foreach (var tweet in userTweetResponse.userTweetsList)
        {
            Items.Add(tweet.ToString());
        }
    }
    isLoading = false;
    

    }

    But still not entering into the hit bottom if block:

     if (e.Item.ToString() == Items[Items.Count - 1])
      {
       } 
    
  • CharwakaCharwaka INMember ✭✭✭✭✭

    @Sreeee said:
    Inside of LoadItems(), I add the code for Items using foreach:

    public async void LoadItems()
     {
      isLoading = true;
      HttpClient client = new HttpClient();
      var response = await client.GetAsync("My Url");
      string tweetJson = await response.Content.ReadAsStringAsync();
    
    UserTweetResponse userTweetResponse = new UserTweetResponse();
    if (tweetJson != "")
    {
        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
        foreach (var tweet in userTweetResponse.userTweetsList)
        {
            Items.Add(tweet.ToString());
        }
    }
    isLoading = false;
    

    }

    But still not entering into the hit bottom if block:

     if (e.Item.ToString() == Items[Items.Count - 1])
      {
       } 
    

    i'm asking URL ,please provide URL which ur hitting

  • CharwakaCharwaka INMember ✭✭✭✭✭
    edited December 2017

    hi @Sreeee

    Make Sure your getting repose from your webservice Call or this wont work

    using System;
    using System.Diagnostics;
    using System.Net.Http;
    using Newtonsoft.Json;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    using System.Collections.ObjectModel;
    using System.Threading.Tasks;
    
    namespace SmartTweet
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class DashBoardPage : ContentPage
        {
            int i = 1;
            bool loadMore;
            ObservableCollection<string> Items;
            bool isLoading;
    
            public DashBoardPage()
            {
                InitializeComponent();
    
                Items = new ObservableCollection<string>();
                var listview = new ListView();
    
                listview.ItemsSource = Items;
                listview.ItemAppearing += (sender, e) =>
                {
                    if (isLoading || Items.Count == 0)
                        return;
    
                    //hit bottom!
                    if (e.Item.ToString() == Items[Items.Count - 1])
                    {
                        Debug.WriteLine("Enter bottom");
                        loadMore = true;
                        Task.Run(async () =>
                        {
                            await UserTweetsList();
    
                        });
    
                    }
                };
    
            }
            protected async override void OnAppearing()
            {
    
                await UserTweetsList();
                base.OnAppearing();
            }
          async  void ButtonClicked(Object sender, EventArgs e)
            {
                loadMore = true;
                await UserTweetsList();
            }
    
            public async Task UserTweetsList()
            {
                isLoading = true;
                if (loadMore)
                {
                    i = i + 1;
                }
                int countInInt = i * 3;
                try
                {
                    string applicationId = "1";
                    string siteId = "5";
                    string userId = "225";
                    string ownedBy = "me";
                    string period = "before";
                    string count = countInInt.ToString();
    
                    DateTime dt = DateTime.Now.ToLocalTime();
                    string date = dt.Year.ToString() + "-" + dt.Month.ToString() + "-" + dt.Day.ToString() + " " + dt.Hour.ToString() + ":" + dt.Minute.ToString() + ":" + dt.Second.ToString() + "." + dt.Millisecond.ToString();
    
                        HttpClient client = new HttpClient();
                        var response = await client.GetAsync("http://54.208.96.132:8090/smartwcm-admin/rest/v3/tweet/usertweetshb/applicationid/" + applicationId + "/siteid/" + siteId + "/userid/" + userId + "/ownedby/" + ownedBy + "/date/" + date + "/period/" + period + "/count/" + count + "?swcmTicket=69f2ed48-6850-4e0f-a2e9-90b54c50fd28");
                        string tweetJson = await response.Content.ReadAsStringAsync();
                        Debug.WriteLine("tweetList:>" + tweetJson);
    
                        UserTweetResponse userTweetResponse = new UserTweetResponse();
                        if (tweetJson != "")
                        {
                            userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
                            foreach (var tweet in userTweetResponse.userTweetsList)
                            {
                                Items.Add(String.Format(tweet.ToString()));
                                //Items.Add(tweet.ToString());
                            }
                        }
                        ListView1.ItemsSource = userTweetResponse.userTweetsList;
                        isLoading = false;
                        if (userTweetResponse.userTweetsList.Count == 0)
                        {
                            //loadMoreButton.IsVisible = false;
                            blue_holo_circle.IsVisible = false;
                            blueLine.IsVisible = false;
                        }
                        else
                        {
                            //loadMoreButton.IsVisible = true;
                            blue_holo_circle.IsVisible = true;
                            blueLine.IsVisible = true;
                        }
    
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
                }
            }
        }
    }
    
  • SreeeeSreeee INMember ✭✭✭✭✭

    Hi @Charwaka
    Apply this code, Still not entering into the if block of hit bottom. Webservice working fine.

  • CharwakaCharwaka INMember ✭✭✭✭✭

    @Sreeee said:
    Hi @Charwaka
    Apply this code, Still not entering into the if block of hit bottom. Webservice working fine.

    Check what your getting here

    if (e.Item.ToString() == Items[Items.Count - 1])

    make sure they are both same thn only it wil enter

  • CharwakaCharwaka INMember ✭✭✭✭✭
    Accepted Answer

    Hi @Sreeee

    paste this whole , it will work

    using System;
    using System.Diagnostics;
    using System.Net.Http;
    using Newtonsoft.Json;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    using System.Collections.ObjectModel;
    using System.Threading.Tasks;
    
    namespace SmartTweet
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class DashBoardPage : ContentPage
        {
            int i = 1;
            bool loadMore;
            ObservableCollection<UserTweetsList> Items =new ObservableCollection<SmartTweet.UserTweetsList>();
            bool isLoading;
            UserTweetResponse userTweetResponse;
            public DashBoardPage()
            {
                InitializeComponent();
    
    
    
                ListView1.ItemAppearing += (sender, e) =>
                {
                    if (isLoading || Items!=null &&  Items.Count == 0)
                        return;
    
                    //hit bottom
                    if (userTweetResponse.userTweetsList!=null && userTweetResponse.userTweetsList.Count>0)
                    {
                        UserTweetsList item = userTweetResponse.userTweetsList[userTweetResponse.userTweetsList.Count - 1];
                        if ((e.Item as UserTweetsList).tweetId.ToString() == item.tweetId.ToString())
                        {
                            Debug.WriteLine("Enter bottom");
                            loadMore = true;
                            UserTweetsList();
    
                        }
                    }
    
    
                };
    
            }
            protected async override void OnAppearing()
            {
                await UserTweetsList();
    
    
                base.OnAppearing();
            }
            async void ButtonClicked(Object sender, EventArgs e)
            {
                loadMore = true;
               // await UserTweetsList();
            }
    
            public async Task UserTweetsList()
            {
                isLoading = true;
                if (loadMore)
                {
                    i = i + 1;
                }
                int countInInt = i * 3;
                try
                {
                    string applicationId = "1";
                    string siteId = "5";
                    string userId = "225";
                    string ownedBy = "me";
                    string period = "before";
                    string count = countInInt.ToString();
    
                    DateTime dt = DateTime.Now.ToLocalTime();
                    string date = dt.Year.ToString() + "-" + dt.Month.ToString() + "-" + dt.Day.ToString() + " " + dt.Hour.ToString() + ":" + dt.Minute.ToString() + ":" + dt.Second.ToString() + "." + dt.Millisecond.ToString();
    
                    HttpClient client = new HttpClient();
                    var response = await client.GetAsync("http://54.208.96.132:8090/smartwcm-admin/rest/v3/tweet/usertweetshb/applicationid/" + applicationId + "/siteid/" + siteId + "/userid/" + userId + "/ownedby/" + ownedBy + "/date/" + date + "/period/" + period + "/count/" + count + "?swcmTicket=69f2ed48-6850-4e0f-a2e9-90b54c50fd28");
                    string tweetJson = await response.Content.ReadAsStringAsync();
                    Debug.WriteLine("tweetList:>" + tweetJson);
    
                     userTweetResponse = new UserTweetResponse();
                    if (tweetJson != "")
                    {
                        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
                        foreach (var tweet in userTweetResponse.userTweetsList)
                        {
                            if (!Items.Contains(tweet))
                            {
                                Items.Add(tweet);
                            }
    
                            //Items.Add(tweet.ToString());
                        }
                    }
                    ListView1.ItemsSource = userTweetResponse.userTweetsList;
                    isLoading = false;
                    if (userTweetResponse.userTweetsList.Count == 0)
                    {
                        //loadMoreButton.IsVisible = false;
                        blue_holo_circle.IsVisible = false;
                        blueLine.IsVisible = false;
                    }
                    else
                    {
                        //loadMoreButton.IsVisible = true;
                        blue_holo_circle.IsVisible = true;
                        blueLine.IsVisible = true;
                    }
    
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
                }
            }
        }
    }
    
  • SreeeeSreeee INMember ✭✭✭✭✭

    @Charwaka said:
    Hi @Sreeee

    paste this whole , it will work

    using System;
    using System.Diagnostics;
    using System.Net.Http;
    using Newtonsoft.Json;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    using System.Collections.ObjectModel;
    using System.Threading.Tasks;
    
    namespace SmartTweet
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class DashBoardPage : ContentPage
        {
            int i = 1;
            bool loadMore;
            ObservableCollection<UserTweetsList> Items =new ObservableCollection<SmartTweet.UserTweetsList>();
            bool isLoading;
            UserTweetResponse userTweetResponse;
            public DashBoardPage()
            {
                InitializeComponent();
    
               
    
                ListView1.ItemAppearing += (sender, e) =>
                {
                    if (isLoading || Items!=null &&  Items.Count == 0)
                        return;
    
                    //hit bottom
                    if (userTweetResponse.userTweetsList!=null && userTweetResponse.userTweetsList.Count>0)
                    {
                        UserTweetsList item = userTweetResponse.userTweetsList[userTweetResponse.userTweetsList.Count - 1];
                        if ((e.Item as UserTweetsList).tweetId.ToString() == item.tweetId.ToString())
                        {
                            Debug.WriteLine("Enter bottom");
                            loadMore = true;
                            UserTweetsList();
    
                        }
                    }
                  
                  
                };
    
            }
            protected async override void OnAppearing()
            {
                await UserTweetsList();
    
               
                base.OnAppearing();
            }
            async void ButtonClicked(Object sender, EventArgs e)
            {
                loadMore = true;
               // await UserTweetsList();
            }
    
            public async Task UserTweetsList()
            {
                isLoading = true;
                if (loadMore)
                {
                    i = i + 1;
                }
                int countInInt = i * 3;
                try
                {
                    string applicationId = "1";
                    string siteId = "5";
                    string userId = "225";
                    string ownedBy = "me";
                    string period = "before";
                    string count = countInInt.ToString();
    
                    DateTime dt = DateTime.Now.ToLocalTime();
                    string date = dt.Year.ToString() + "-" + dt.Month.ToString() + "-" + dt.Day.ToString() + " " + dt.Hour.ToString() + ":" + dt.Minute.ToString() + ":" + dt.Second.ToString() + "." + dt.Millisecond.ToString();
    
                    HttpClient client = new HttpClient();
                    var response = await client.GetAsync("http://54.208.96.132:8090/smartwcm-admin/rest/v3/tweet/usertweetshb/applicationid/" + applicationId + "/siteid/" + siteId + "/userid/" + userId + "/ownedby/" + ownedBy + "/date/" + date + "/period/" + period + "/count/" + count + "?swcmTicket=69f2ed48-6850-4e0f-a2e9-90b54c50fd28");
                    string tweetJson = await response.Content.ReadAsStringAsync();
                    Debug.WriteLine("tweetList:>" + tweetJson);
    
                     userTweetResponse = new UserTweetResponse();
                    if (tweetJson != "")
                    {
                        userTweetResponse = JsonConvert.DeserializeObject<UserTweetResponse>(tweetJson.ToString());
                        foreach (var tweet in userTweetResponse.userTweetsList)
                        {
                            if (!Items.Contains(tweet))
                            {
                                Items.Add(tweet);
                            }
                           
                            //Items.Add(tweet.ToString());
                        }
                    }
                    ListView1.ItemsSource = userTweetResponse.userTweetsList;
                    isLoading = false;
                    if (userTweetResponse.userTweetsList.Count == 0)
                    {
                        //loadMoreButton.IsVisible = false;
                        blue_holo_circle.IsVisible = false;
                        blueLine.IsVisible = false;
                    }
                    else
                    {
                        //loadMoreButton.IsVisible = true;
                        blue_holo_circle.IsVisible = true;
                        blueLine.IsVisible = true;
                    }
    
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
                }
            }
        }
    }
    

    I apply this code, getting nullreference exception on the hit bottom if block...

  • CharwakaCharwaka INMember ✭✭✭✭✭

    @Selvamz said:
    You can try Syncfusion SfListView which has support to load more items automatically when end of list reached by default.
    https://help.syncfusion.com/xamarin/sflistview/loadmore
     
    You can check out the samples from android store and iTunes.
    https://play.google.com/store/apps/details?id=com.syncfusion.samplebrowser
    https://itunes.apple.com/us/app/syncfusion-controls-explorer/id1109963411?mt=8"
     
    Refer: ListView -> Load More sample for your requirement.

     
    Syncfusion controls is available for free through the community license program if you qualify (less than 1 million USD in revenue).
    Note: I work for Syncfusion.

    it would cost him more $$$ in Enterprise level

  • SreeeeSreeee INMember ✭✭✭✭✭

    Hi @Charwaka I also implement stop calling web service after all items listed B)

Sign In or Register to comment.