SfListView get totalItems count from web service before check load more items not work

hello how are you , please i have problem with load more list view how to get total items from web service before checkCanLoadMoreItems . because the web service use await i get total items always 0 before check if (Events.Count >= totalItems) 10 days no solution i use wait function the main thread in stopped . this is code
public class EventViewModel : INotifyPropertyChanged
{
#region Evenets
private void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region Attributes
private ApiService apiService;
private DialogService dialogService;
private NavigationService navigationService;
private int totalItems=0 ;
#endregion
#region Properties
public ObservableCollection Events { get; set; }
public Command<object> LoadMoreItemsCommand { get; set; }
#endregion
#region Constructors
public EventViewModel()
{
apiService = new ApiService();
dialogService = new DialogService();
navigationService = new NavigationService();
Events = new ObservableCollection();
LoadMoreItemsCommand = new Command<object>(LoadMoreItems, CanLoadMoreItems);
}
private bool CanLoadMoreItems(object obj)
{
totalItems = (int) EventCount().Result;
dialogService.ShowMessage("Number of items from web service", totalItems.ToString());
//always get 0 because await it is not finish
if (Events.Count >= totalItems)
return false;
return true;
}
private async void LoadMoreItems(object obj)
{
var listview = obj as Syncfusion.ListView.XForms.SfListView;
listview.IsBusy = true;
var index = Events.Count;
var count = index + 3 >= totalItems ? totalItems - index : 3;
await LoadEvents(index, count);
listview.IsBusy = false;
}
// function for get totalItems count from web service
private async Task EventCount()
{
var urlBase = Application.Current.Resources["URLBase"].ToString();
var response = await apiService.GetCount(
urlBase,
"/api",
"/Eventcount",
Settings.TokenType,
Settings.Token);
if (!response.IsSuccess)
{
await dialogService.ShowMessage("Error", response.Message);
return null;
}
return response;
}
// function for get only 3 items from web service
private async Task LoadEvents(int index, int count)
{
var urlBase = Application.Current.Resources["URLBase"].ToString();
// var user = dataService.First(false);
var user = MainViewModel.GetInstance().CurrentUser;
var response = await apiService.Get(
urlBase,
"/api",
"/Events",
index,
count,
Settings.TokenType,
Settings.Token);
if (!response.IsSuccess)
{
await dialogService.ShowMessage("Error", response.Message);
return;
}
ReloadEvents((List)response.Result);
}
private void ReloadEvents(List tournaments)
{
foreach (var tournament in tournaments)
{
Events.Add(new EventItemViewModel
{
EventId = tournament.EventId,
UserId = tournament.UserId,
Name = tournament.Name,
Date = tournament.Date,
Place = tournament.Place,
Description = tournament.Description,
Latitude = tournament.Latitude,
Longitude = tournament.Longitude,
User = tournament.User,
EventUsers = tournament.EventUsers,
});
}
}


3 Replies

MK Muthu Kumaran Gnanavinayagam Syncfusion Team July 5, 2018 01:27 PM UTC

Hi Samialfarra, 
 
We have checked the reported query at our end. While loading items into the collection asynchronously, the items may not be fetched from the server. So you can check for zero collection count before loading the items in the View. 
 
Based on your requirement, we have created a sample and you can download it from the below link. 
 
 
Please let us know if you require further assistance. 
 
Regards, 
G.Muthu kumaran. 



SA samialfarra July 9, 2018 10:28 PM UTC

thank you for reply but i can not merge my code with this is example becaue i am not feteching all data at once i use this web api 


//-----------------------------Web API Get Event By PageIndex and Pagesize (Skip and Take) ------------------------------------------------------


  // GET: api/Events
        [Route("api/Events/{pageIndex}/{pageSize}")]
        public async Task<IHttpActionResult> GetEvents(int pageIndex , int pageSize)
        {

            var events = await db.Events.Where(d=>d.IsEnables==true).OrderByDescending(c => c.EventId).Skip(pageIndex ).Take(pageSize).ToListAsync();
            var list = new List<EventResponse>();

            foreach (var ev in events )   
            
            {
                list.Add(new EventResponse
                {
                    EventId = ev.EventId,
                    UserId = ev.UserId,
                    Name = ev.Name,
                    Date = ev.Date,
                    Place = ev.Place,
                    Description = ev.Description,
                    Latitude = ev.Latitude,
                    Longitude = ev.Longitude,
                    User = ev.User,
                    EventUsers = ev.EventUsers.ToList(),
                    IsEnables = ev.IsEnables
                    
                });
            }
            return Ok(list);
        }


//--------------------------Web API Get EventsCount-------------------

   public async Task<int> GetEventCounts()
        {
            return  db.Events.Count();
        }


//------------------------RestApiService in xamarin forms  Get and GetCount-----------------------------

  public class ApiService
    {

         public async Task<Response> Get<T>(string urlBase, string servicePrefix, string controller,int pageIndex, int pageSize, string tokenType, string accessToken)
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
                client.BaseAddress = new Uri(urlBase);
                var url = string.Format("{0}{1}/{2}/{3}", servicePrefix, controller,pageIndex,pageSize);
                var response = await client.GetAsync(url);

                if (!response.IsSuccessStatusCode)
                {
                    return new Response
                    {
                        IsSuccess = false,
                        Message = response.StatusCode.ToString(),
                    };
                }

                var result = await response.Content.ReadAsStringAsync();
                var list = JsonConvert.DeserializeObject<List<T>>(result);
                return new Response
                {
                    IsSuccess = true,
                    Message = "Ok",
                    Result = list,
                };
            }
            catch (Exception ex)
            {
                return new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                };
            }
        }






 public async Task<Response> GetCount<T>(string urlBase, string servicePrefix, string controller, string tokenType, string accessToken)
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
                client.BaseAddress = new Uri(urlBase);
                var url = string.Format("{0}{1}", servicePrefix, controller);
                var response = await client.GetAsync(url);

                if (!response.IsSuccessStatusCode)
                {
                    return new Response
                    {
                        IsSuccess = false,
                        Message = response.StatusCode.ToString(),
                    };
                }

                var result = await response.Content.ReadAsStringAsync();
                var list = JsonConvert.DeserializeObject<T>(result);
                return new Response
                {
                    IsSuccess = true,
                    Message = "Ok",
                    Result = list,
                };
            }
            catch (Exception ex)
            {
                return new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                };
            }
        }





}




VR Vigneshkumar Ramasamy Syncfusion Team July 10, 2018 01:04 PM UTC

Hi Samialfarra,  
  
Sorry for the inconvenience.  
  
It is not possible to get the count when load the data asynchronously. We would like to let you know that you can achieve your requirement by showing the busy indicator when get the count from the web service like below code snippet.  
  
Code Example[C#]:  
public async Task<int> GetEventCounts()  
            {  
                if (db.Events.Count == 0)  
                    IsBusy = true;  
                else  
                    IsBusy = false;  
  
                return db.Events.Count();  
            }  
  
Please let us know if you require further assistance.  
 
Regards 
Vigneshkumar R 


Loader.
Up arrow icon