Forum Xamarin Xamarin.Forms

CollectionView index crash

edyboyedyboy Member ✭✭✭

Hello everyone

I have an error with my code, that I can't figure out

I have a collectionView, and when I press "Editar mascota" and "Cancelar"

I get this error

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'

Note: I have a viewModel and I already supply the data to that collectionview with this view view Model

class MyMascotasViewModel : ViewModelBase {
        private ObservableCollection<Pet> _pets;
        public ObservableCollection<Pet> Pets {
            get {
                return _pets;
            }
            set {
                _pets = value;
                RaisePropertyChanged("Pets");
            }
        }

        IAuth auth;

        public MyMascotasViewModel() {
            Pets = new ObservableCollection<Pet>();

            auth = DependencyService.Get<IAuth>();

            GetData();
        }
        public async void GetData() {

            var document = await CrossCloudFirestore.Current
                                      .Instance
                                      .GetCollection("Pets")
                                      .WhereEqualsTo("Owner", auth.GetUserDisplayName())
                                      .GetDocumentsAsync();



            var p = document.ToObjects<Pet>();

            Pets.Clear();
            foreach (var item in p) {

                Pets.Add(item);
            }
        }
    }
}
 Pet p = e.CurrentSelection[0] as Pet;

            System.Diagnostics.Debug.WriteLine(e.CurrentSelection[0]);

            if (p != null) {
                string uid = string.Empty;
                string action = await DisplayActionSheet(null, null,
                          null, "¿Que desea ejecutar?", "Eliminar mascota", "Editar mascota", "Cancelar");

                switch (action) {

                    case "Eliminar mascota":
                        myMascotasViewModel.Pets.Remove(p);

                        var query = await CrossCloudFirestore.Current
                              .Instance
                              .GetCollection(Constants.PETS)
                              .WhereEqualsTo("Id", p.Id)
                              .GetDocumentsAsync();

                        foreach (var item in query.Documents) {
                            uid = item.Id;
                        }

                        await CrossCloudFirestore.Current
                                 .Instance
                                 .GetCollection(Constants.PETS)
                                 .GetDocument($"{uid}")
                                 .DeleteDocumentAsync();

                        break;
                    case "Editar mascota":
                        await Navigation.PushAsync(new EditPet(p));
                        ((CollectionView)sender).SelectedItem = null;
                        break;
                    default:
                        ((CollectionView)sender).SelectedItem = null;
                        break;
                }

Answers

  • ColeXColeX Member, Xamarin Team Xamurai

    Could you firstly use debugger to clarify which line causes the error ?

  • edyboyedyboy Member ✭✭✭

    the problem happen when I want to navigate

  • ColeXColeX Member, Xamarin Team Xamurai
    edited September 11

    @edyboy said:
    the problem happen when I want to navigate

    Which code triggers when you do navigate ?

  • edyboyedyboy Member ✭✭✭
      private async void PetList_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e) {
    
                Pet item = e.ItemData as Pet;
    
                Debug.WriteLine(myMascotasViewModel.Pets.IndexOf(item));
    
                bool answer = await DisplayAlert("IMPORTANTE", $"Desea editar a {item.Nombre}", "Si", "No");
    
                switch (answer) {
                    case true:
                        //await Navigation.PushAsync(new EditPet(item)); // here will crash
                        break;
                    default:
                        PetList.SelectedItems.Clear();
                        break;
    
                }
            }
    

    The strange part is tha when I print the index, it will give me the exact index I am

  • edyboyedyboy Member ✭✭✭

    this is my entire code behind

       private async void FabBtn_Clicked(object sender, System.EventArgs e) {
    
                string accion = await DisplayActionSheet(null, "Cancelar",
                      null, "Usar camara", "Elegir de la galería", null);
    
    
                switch (accion) {
    
                    case "Usar camara":
                        mediaFile = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions {
                            Directory = "AppetLand Photos",
                            SaveToAlbum = true,
                            DefaultCamera = CameraDevice.Front
                        });
    
                        if (mediaFile == null) {
                            return;
                        }
                        img = ImageSource.FromStream(() => mediaFile.GetStream());
    
                        mascotaImg = await StoreImages(mediaFile.GetStream(), "Imagen principal", Path.GetExtension(mediaFile.Path));
    
                        Preferences.Set("Mascota Prinpipal", mascotaImg);
    
                        await Navigation.PushAsync(new PetInfoScreen(mascotaImg));
                        break;
                    case "Elegir de la galería":
                        mediaFile = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions { });
    
                        if (mediaFile == null) {
                            return;
                        }
                        img = ImageSource.FromStream(() => mediaFile.GetStream());
    
                        mascotaImg = await StoreImages(mediaFile.GetStream(), "Imagen principal", Path.GetExtension(mediaFile.Path));
    
                        Preferences.Set("Mascota Prinpipal", mascotaImg);
    
                        await Navigation.PushAsync(new PetInfoScreen(mascotaImg));
    
                        break;
                    default:
                        break;
                }
            }
    
            protected override void OnAppearing() {
                base.OnAppearing();
    
                myMascotasViewModel.GetData();
                PetList.ItemsSource = myMascotasViewModel.Pets;
            }
    
            //private void TapRegonizer_Tapped(object sender, System.EventArgs e) {
    
            //}
    
            public async Task<string> StoreImages(Stream imageStream, string name, string ext) {
    
                var stroageImage = await new FirebaseStorage("apetland.appspot.com")
                    .Child(auth.GetUserCurrentID())
                    .Child($"{name}{ext}")
                    .PutAsync(imageStream);
                string imgurl = stroageImage;
                return imgurl;
            }
    
            private async void PetList_ItemTapped(object sender, Syncfusion.ListView.XForms.ItemTappedEventArgs e) {
    
                Pet item = e.ItemData as Pet;
    
                Debug.WriteLine(myMascotasViewModel.Pets.Count);
                Debug.WriteLine($"hello a am {item.Nombre} and this is my index {myMascotasViewModel.Pets.IndexOf(item)}");
    
    
    
                bool answer = await DisplayAlert("IMPORTANTE", $"Desea editar a {item.Nombre}", "Si", "No");
    
                switch (answer) {
                    case true:
                        //await Navigation.PushAsync(new EditPet(item));
                        break;
                    default:
                        PetList.SelectedItems.Clear();
                        break;
    
                }
            }
    
            private async void PetList_ItemHolding(object sender, Syncfusion.ListView.XForms.ItemHoldingEventArgs e) {
    
                var p = e.ItemData as Pet;
    
                bool answer = await DisplayAlert(string.Empty, $"Desea eliminar a {p.Nombre}", "Si", "No");
    
                switch (answer) {
                    case true:
    
                        myMascotasViewModel.Pets.Remove(p);
    
                        var query = await CrossCloudFirestore.Current
                              .Instance
                              .GetCollection(Constants.PETS)
                              .WhereEqualsTo("Id", p.Id)
                              .GetDocumentsAsync();
    
                        foreach (var item in query.Documents) {
                            uid = item.Id;
                        }
    
                        await CrossCloudFirestore.Current
                                 .Instance
                                 .GetCollection(Constants.PETS)
                                 .GetDocument($"{uid}")
                                 .DeleteDocumentAsync();
                        break;
                    default:
                        break;
                }
    
    
    
                PetList.SelectedItem = null;
            }
    
  • ColeXColeX Member, Xamarin Team Xamurai

    Pls post the code in EditPet page .

  • DanielHJDanielHJ Member ✭✭
    edited September 17

    **Edit: Never mind, it's too late in the day and I missed a method that was being called. Good luck to you!
    **
    I am getting the same error when I scroll in my CollectionView. Mine is not exactly the same tho..

    I have grouped collectionview with a header, groupheader, items, groupfooter and footer. When I press the searchbar, the keyboard appears and the collectionview scrolls down a bit. Now when I scroll I get index out of range. But it only seems to happen when I have written some text in the Searchbar, which makes no sense to me ^^

    System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index
      at System.Collections.Generic.List`1[T].get_Item (System.Int32 index) [0x00009] in <85a0be741dba4068b8b83c4563af7fa8>:0
      at System.Collections.Generic.List`1[T].System.Collections.IList.get_Item (System.Int32 index) [0x00000] in <85a0be741dba4068b8b83c4563af7fa8>:0
      at Xamarin.Forms.Platform.iOS.ObservableGroupedSource.Group (Foundation.NSIndexPath indexPath) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableGroupedSource.cs:79
      at Xamarin.Forms.Platform.iOS.GroupableItemsViewController`1[TItemsView].UpdateTemplatedSupplementaryView (Xamarin.Forms.Platform.iOS.TemplatedCell cell, Foundation.NSString elementKind, Foundation.NSIndexPath indexPath) [0x00036] in <7cbae75e123c467eb27876e5c72d7719>:0
      at Xamarin.Forms.Platform.iOS.GroupableItemsViewController`1[TItemsView].GetViewForSupplementaryElement (UIKit.UICollectionView collectionView, Foundation.NSString elementKind, Foundation.NSIndexPath indexPath) [0x00033] in <7cbae75e123c467eb27876e5c72d7719>:0
      at at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
      at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/UIKit/UIApplication.cs:86
      at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0000e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/UIKit/UIApplication.cs:65
      at WasteCollection.iOS.Application.Main (System.String[] args) [0x00001]
    
  • PetursigPetursig Member

    I am running into the same issue, whenever I try to modify a ObservableCollection that is bound to a CollectioView, the iOS Device crashes with the same error as mentioned before. I removed the binding and set a List<> directly to the ItemsSource. This fixed it on one page, but this error is still lurking and still pops up on other views.

  • PetursigPetursig Member

    I am running into a similar issue, Whenever I try to clear the selection I get the following:

    {System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index at System.Collections.Generic.List1[T].get_Item (System.Int32 index) [0x00009] in <b2309b0f34c14f2999df87941bbffcf9>:0 at System.Collections.ObjectModel.Collection1[T].System.Collections.IList.get_Item (System.Int32 index) [0x00000] in :0
    at Xamarin.Forms.Platform.iOS.ObservableItemsSource.ElementAt (System.Int32 index) [0x0000f] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:254
    at Xamarin.Forms.Platform.iOS.ObservableItemsSource.get_Item (System.Int32 index) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:40
    at Xamarin.Forms.Platform.iOS.ObservableItemsSource.get_Item (Foundation.NSIndexPath indexPath) [0x00019] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:96
    at Xamarin.Forms.Platform.iOS.ItemsViewController1[TItemsView].UpdateTemplatedCell (Xamarin.Forms.Platform.iOS.TemplatedCell cell, Foundation.NSIndexPath indexPath) [0x00029] in <3518962be2ba44b7b4403d0528b0f783>:0 at Xamarin.Forms.Platform.iOS.ItemsViewController1[TItemsView].GetCell (UIKit.UICollectionView collectionView, Foundation.NSIndexPath indexPath) [0x00033] in <3518962be2ba44b7b4403d0528b0f783>:0
    at Xamarin.Forms.Platform.iOS.ItemsViewController`1[TItemsView].GetPrototype () [0x00064] in <3518962be2ba44b7b4403d0528b0f783>:0
    at Xamarin.Forms.Platform.iOS.ItemsViewLayout.DetermineCellSize () [0x0004e] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewLayout.cs:201
    at Xamarin.Forms.Platform.iOS.ListViewLayout.ConstrainTo (CoreGraphics.CGSize size) [0x0001e] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ListViewLayout.cs:16
    at Xamarin.Forms.Platform.iOS.ItemsViewLayout.UpdateConstraints (CoreGraphics.CGSize size) [0x0003f] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewLayout.cs:96
    at Xamarin.Forms.Platform.iOS.ItemsViewLayout.InvalidateLayout () [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewLayout.cs:535
    at (wrapper managed-to-native) ObjCRuntime.Messaging.void_objc_msgSend(intptr,intptr)
    at UIKit.UICollectionView.ReloadData () [0x0000d] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/UIKit/UICollectionView.g.cs:690
    at Xamarin.Forms.Platform.iOS.ObservableItemsSource.Reload () [0x00071] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:142
    at Xamarin.Forms.Platform.iOS.ObservableItemsSource.CollectionChanged (System.Collections.Specialized.NotifyCollectionChangedEventArgs args) [0x00198] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:129
    at Xamarin.Forms.Platform.iOS.ObservableItemsSource.CollectionChanged (System.Object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs args) [0x000b7] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:108
    at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__7_0 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
    at Foundation.NSAsyncSynchronizationContextDispatcher.Apply () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/Foundation/NSAction.cs:178
    at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
    at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/UIKit/UIApplication.cs:86
    at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0000e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/UIKit/UIApplication.cs:65
    at ReglaPosMobile.iOS.Application.Main (System.String[] args) [0x00044] in C:\VSS2002\Paperless\POS\ReglaPOS2\ReglaPosMobile\ReglaPosMobile.iOS\Main.cs:32 }

  • jrrjrr Member ✭✭

    I am encountering the same error when I pull down to refresh my CollectionView, that is wrapped in a RefreshView in my xamarin project. The CollectionView is bound to an ObservableCollection that is updated on the pull down refresh.

    System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index
      at System.Collections.Generic.List`1[T].get_Item (System.Int32 index) [0x00009] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/Common/src/CoreLib/System/Collections/Generic/List.cs:161
      at System.Collections.ObjectModel.Collection`1[T].System.Collections.IList.get_Item (System.Int32 index) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/external/corefx/src/Common/src/CoreLib/System/Collections/ObjectModel/Collection.cs:266
      at Xamarin.Forms.Platform.iOS.ObservableItemsSource.ElementAt (System.Int32 index) [0x0000f] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:254
      at Xamarin.Forms.Platform.iOS.ObservableItemsSource.get_Item (System.Int32 index) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:40
      at Xamarin.Forms.Platform.iOS.ObservableItemsSource.get_Item (Foundation.NSIndexPath indexPath) [0x00019] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:96
      at Xamarin.Forms.Platform.iOS.ItemsViewController`1[TItemsView].UpdateTemplatedCell (Xamarin.Forms.Platform.iOS.TemplatedCell cell, Foundation.NSIndexPath indexPath) [0x00012] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewController.cs:199
      at Xamarin.Forms.Platform.iOS.ItemsViewController`1[TItemsView].GetCell (UIKit.UICollectionView collectionView, Foundation.NSIndexPath indexPath) [0x00033] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewController.cs:84
      at at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
      at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Library/Frameworks/Xamarin.iOS.framework/Versions/14.0.0.0/src/Xamarin.iOS/UIKit/UIApplication.cs:86
      at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) 
    
  • jrrjrr Member ✭✭

    Now, I see it even when I navigate away from the page with the CollectionView, and come back to it. So it throws even on page appear when the CollectionView is populated from the ObservableCollection.

  • edyboyedyboy Member ✭✭✭

    I fixed the error, there was something null in the edit page

  • jrrjrr Member ✭✭

    Seems to be related to running the app on iOS 14. Don't see the issue on my iOS 13 device.

  • jonathannicholsjonathannichols USMember ✭✭

    We are also getting this error on iOS 14 and were hoping to release today.

  • NicoleLuNicoleLu Member, Xamarin Team Xamurai

    Hi @jrr, you mean same code is working on iOS 13 but not working on iOS 14? Please consider file an issue in github, I do see some issue is reporting similar error messages but not exactly same with yours in the issue list(like this one), but engineer is just not able to reproduce, it would be helpful if you can provide more info to help locate the issue and finally resolve it.

  • jrrjrr Member ✭✭

    @NicoleLu I don't see the error again after updating to Xamarin Forms 4.8.0.1534.

  • NicoleLuNicoleLu Member, Xamarin Team Xamurai
    edited October 19

    @jrr Thank you for confirmation
    @Petursig @jonathannichols are you still getting this error with latest XF? If issue still exists, you can open a new thread to elaborate your problem or follow and provide some information in github: https://github.com/xamarin/Xamarin.Forms/issues/12080 and https://github.com/xamarin/Xamarin.Forms/issues/12502

Sign In or Register to comment.