Mauricio Cárdenas
Mauricio Cárdenas

Reputation: 484

Cannot refresh listview with observablecollection

I am trying to refresh my listview when an item is removed from it, but every time it gives me this error:

System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index.

Before updating the ObservableCollection, I do this:

    Groups = new ObservableCollection<RequestGroups>();

And then I fill it with this:

    var temp = (JArray)resultJson["data"];
            JArray jarr = temp;
            foreach (JObject contents in jarr.Children<JObject>())
            {
                Requests obj = new Requests();
                obj.Id = (int)contents["id"];
                Client c = new Client();
                c.address = contents["address"].ToString();
                c.phone = contents["phone"].ToString();
                c.name = contents["user"].ToString();
                obj.Client = c;
                obj.Date = contents["date"].ToString();
                obj.Duration = contents["duration"].ToString();
                obj.DurationText = "Duración: "+contents["duration"].ToString()+"h";
                obj.Price = "$" + contents["price"].ToString();
                String[] cDate = obj.Date.Split(' ');
                String cHour = cDate[1]+" "+cDate[2];
                obj.Hour = cHour;
                String[] date = cDate[0].Split('-');
                String title = months[date[1]] + " " + date[0];
                obj.Title = title;
                bool flag = false;
                foreach(RequestGroups rqG in Groups){
                    if(rqG.Title.Equals(title)){
                        rqG.Add(obj);
                        flag = true;
                    }
                }
                if(!flag){
                    RequestGroups rq = new RequestGroups(title, date[1] + "-" + date[0]);
                    rq.Add(obj);
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        Groups.Add(rq);
                    });
                }

            }

This is where I remove the items:

    private async Task UpdateRequest(int status,int idEvent)
    {
        HttpClient hTTPClient = new HttpClient();
        var client = new HttpClient();
        client.Timeout = TimeSpan.FromSeconds(60);
        client.BaseAddress = new Uri(Utils.baseUrl);

        Dictionary<string, string> dataToSend = new Dictionary<string, string>();
        dataToSend.Add("session", Utils.loginKey);
        dataToSend.Add("eventId", idEvent+"");
        dataToSend.Add("status", status.ToString());
        string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(dataToSend, new KeyValuePairConverter());

        var contentVar = new StringContent(jsonData, Encoding.UTF8, "application/json");
        try
        {
            HttpResponseMessage response = await client.PostAsync("/UpdateEvent", contentVar);
            var result = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                string contents = await response.Content.ReadAsStringAsync();
                var resultJson = JObject.Parse(result);
                if ((int)resultJson["status"] == 0)
                {
                    await base.DisplayAlert((string)resultJson["msg"], "", "OK");
                    return;
                }
                else if ((int)resultJson["status"] == 1)
                {
                    //I'm currently trying to reload the whole view, before this was calling the method above.
                    await this.mainPage.Navigation.PushAsync(new NavigationPage(new MasterMenu.MainPage()));
                    await getRequests();
                }
                else
                {
                    await base.DisplayAlert("Error procesando la solicitud, intente más tarde", "", "Ok");
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Error update request: {0}", ex);
        }
        await Task.Delay(1);
    }

If I leave it like that, UI will not update. Please help me, as I've been struggling with this issue for 2 days now. It happens exclusively on iOS.

Upvotes: 0

Views: 240

Answers (1)

Mauricio C&#225;rdenas
Mauricio C&#225;rdenas

Reputation: 484

The issue was fixed after updating iOS. The problem was caused because of a buggy iOS version that had problems indexing objects. After updating, everything ran as smoothly as usual. If anyone runs into this issue (exclusively on iOS), try updating both iOS and Xamarin Forms.

Upvotes: 1

Related Questions