Skip to content
This repository has been archived by the owner on May 1, 2024. It is now read-only.

[Bug] CarouselView Throws when removing an item. #10865

Closed
Pentadome opened this issue May 27, 2020 · 21 comments · Fixed by #11074
Closed

[Bug] CarouselView Throws when removing an item. #10865

Pentadome opened this issue May 27, 2020 · 21 comments · Fixed by #11074
Assignees
Labels
a/carouselview e/2 🕑 2 i/high Completely doesn't work, crashes, or is unusably slow, has no obvious workaround; occurs less often in-progress This issue has an associated pull request that may resolve it! t/bug 🐛
Milestone

Comments

@Pentadome
Copy link

Pentadome commented May 27, 2020

Description

Steps to Reproduce

  1. Have an ObservableCollection as item source of an carouselview
  2. Remove an item

Expected Behavior

No error

Actual Behavior

ArgumentOutOfRangeException

Basic Information

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 /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/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 /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/Collections/ObjectModel/Collection.cs:266 
  at Xamarin.Forms.Platform.Android.ObservableItemsSource.ElementAt (System.Int32 index) [0x0000f] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\ObservableItemsSource.cs:223 
  at Xamarin.Forms.Platform.Android.ObservableItemsSource.GetItem (System.Int32 position) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\ObservableItemsSource
.cs:59 
  at Xamarin.Forms.Platform.Android.CarouselViewRenderer.SetCurrentItem (System.Int32 carouselPosition) [0x00043] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\CarouselViewRenderer.cs:392 
  at Xamarin.Forms.Platform.Android.CarouselViewRenderer.CollectionItemsSourceChanged (System.Object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) [0x000bc] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\CarouselViewRenderer.cs:256 
  at Xamarin.Forms.Platform.Android.ObservableItemsSource.CollectionChanged (System.Collections.Specialized.NotifyCollectionChangedEventArgs args) [0x0005a] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\ObservableItemsSource.cs:122 
  at Xamarin.Forms.Platform.Android.ObservableItemsSource.CollectionChanged (System.Object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs args) [0x0002d] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\ObservableItemsSource.cs:95 
  at System.Collections.ObjectM
odel.ObservableCollection`1[T].OnCollectionChanged (System.Collections.Specialized.NotifyCollectionChangedEventArgs e) [0x00018] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs:263 
  at System.Collections.ObjectModel.ObservableCollection`1[T].OnCollectionChanged (System.Collections.Specialized.NotifyCollectionChangedAction action, System.Object item, System.Int32 index) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs:338 
  at System.Collections.ObjectModel.ObservableCollection`1[T].RemoveItem (System.Int32 index) [0x00021] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs:182 
  at System.Collections.ObjectModel.Collection`1[T].Remove (T
 item) [0x00027] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/Collections/ObjectModel/Collection.cs:128 
  at Iris_App.ViewModels.AdviceDetailsViewModel+<>c__DisplayClass28_0.<DeleteImage>b__0 () [0x00002] in C:\Users\wrket\Source\Repos\Iris App\Iris_App\Iris_App\ViewModels\Advice\AdviceDetails\Commands\DeleteImageCommand.cs:31 
Microsoft Visual Studio Professional 2019
Version 16.6.0
VisualStudio.16.Release/16.6.0+30114.105
Microsoft .NET Framework
Version 4.8.03752

Installed Version: Professional

ADL Tools Service Provider   1.0
This package contains services used by Data Lake tools

ASA Service Provider   1.0

ASP.NET and Web Tools 2019   16.6.936.3669
ASP.NET and Web Tools 2019

ASP.NET Core Razor Language Services   16.1.0.2020603+b3ac44798c16fff5b95dbcfe62dea84aa9a1bd72
Provides languages services for ASP.NET Core Razor.

ASP.NET Web Frameworks and Tools 2019   16.6.936.3669
For additional information, visit https://www.asp.net/

Azure App Service Tools v3.0.0   16.6.936.3669
Azure App Service Tools v3.0.0

Azure Data Lake Node   1.0
This package contains the Data Lake integration nodes for Server Explorer.

Azure Data Lake Tools for Visual Studio   2.4.6000.0
Microsoft Azure Data Lake Tools for Visual Studio

Azure Functions and Web Jobs Tools   16.6.936.3669
Azure Functions and Web Jobs Tools

Azure Stream Analytics Tools for Visual Studio   2.4.6000.0
Microsoft Azure Stream Analytics Tools for Visual Studio

C# Tools   3.6.0-4.20251.5+910223b64f108fcf039012e0849befb46ace6e66
C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

CodeMaid   11.1.209
CodeMaid is an open source Visual Studio extension to cleanup and simplify our C#, C++, F#, VB, PHP, PowerShell, R, JSON, XAML, XML, ASP, HTML, CSS, LESS, SCSS, JavaScript and TypeScript coding.

Common Azure Tools   1.10
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Extensibility Message Bus   1.2.0 (d16-2@8b56e20)
Provides common messaging-based MEF services for loosely coupled Visual Studio extension components communication and integration.

Fabric.DiagnosticEvents   1.0
Fabric Diagnostic Events

IntelliCode Extension   1.0
IntelliCode Visual Studio Extension Detailed Info

Microsoft Azure HDInsight Azure Node   2.4.6000.0
HDInsight Node under Azure Node

Microsoft Azure Hive Query Language Service   2.4.6000.0
Language service for Hive query

Microsoft Azure Service Fabric Tools for Visual Studio   16.0
Microsoft Azure Service Fabric Tools for Visual Studio

Microsoft Azure Stream Analytics Language Service   2.4.6000.0
Language service for Azure Stream Analytics

Microsoft Azure Stream Analytics Node   1.0
Azure Stream Analytics Node under Azure Node

Microsoft Azure Tools   2.9
Microsoft Azure Tools for Microsoft Visual Studio 2019 - v2.9.30212.1

Microsoft Continuous Delivery Tools for Visual Studio   0.4
Simplifying the configuration of Azure DevOps pipelines from within the Visual Studio IDE.

Microsoft JVM Debugger   1.0
Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft Library Manager   2.1.50+g25aae5a24a.R
Install client-side libraries easily to any web project

Microsoft MI-Based Debugger   1.0
Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual Studio Tools for Containers   1.1
Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit & refresh your app without having to rebuild the container.

Mono Debugging for Visual Studio   16.6.17 (9692114)
Support for debugging Mono processes with Visual Studio.

NuGet Package Manager   5.6.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit https://docs.nuget.org/

ProjectServicesPackage Extension   1.0
ProjectServicesPackage Visual Studio Extension Detailed Info

SQL Server Data Tools   16.0.62004.28040
Microsoft SQL Server Data Tools

ToolWindowHostedEditor   1.0
Hosting json editor into a tool window

TypeScript Tools   16.0.20417.2002
TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools   3.6.0-4.20251.5+910223b64f108fcf039012e0849befb46ace6e66
Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 10.9.1.0 for F# 4.7   16.6.0-beta.20217.4+1c969cac25e2d38d71872efe6c8226029e42bb59
Microsoft Visual F# Tools 10.9.1.0 for F# 4.7

Visual Studio Code Debug Adapter Host Package   1.0
Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Container Tools Extensions (Preview)   1.0
View, manage, and diagnose containers within Visual Studio.

Visual Studio Tools for Containers   1.0
Visual Studio Tools for Containers

Visual Studio Tools for Kubernetes   1.0
Visual Studio Tools for Kubernetes

VisualStudio.DeviceLog   1.0
Information about my package

VisualStudio.Foo   1.0
Information about my package

VisualStudio.Mac   1.0
Mac Extension for Visual Studio

Xamarin   16.6.000.1055 (d16-6@2873694)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer   16.6.0.318 (remotes/origin/d16-6@66afc5421)
Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin Templates   16.6.40 (1f1466f)
Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms.

Xamarin.Android SDK   10.3.1.0 (d16-6/3fe860a)
Xamarin.Android Reference Assemblies and MSBuild support.
    Mono: 165f4b0
    Java.Interop: xamarin/java.interop/d16-6@2cab35c
    ProGuard: xamarin/proguard/master@905836d
    SQLite: xamarin/sqlite/3.31.1@49232bc
    Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-6@bfb66f3


Xamarin.iOS and Xamarin.Mac SDK   13.18.1.31 (b3eedfe)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Xamarin Forms 4.7.0.813-pre2

@Pentadome Pentadome added s/unverified New report that has yet to be verified t/bug 🐛 labels May 27, 2020
@pauldipietro pauldipietro added this to New in Triage May 27, 2020
@jsuarezruiz jsuarezruiz added a/carouselview i/high Completely doesn't work, crashes, or is unusably slow, has no obvious workaround; occurs less often labels May 27, 2020
@samhouts samhouts added this to Backlog in CarouselView May 28, 2020
@jsuarezruiz
Copy link
Contributor

I have tried to reproduce the issue without success. Attached the sample created:
Issue10865.zip
(Tested with Xamarin.Forms 4.6 and 4.7-pre2)

@wrkettlitz Probably we are doing something different, could you review/update the attached sample or attach a reproduction sample?

@jsuarezruiz jsuarezruiz moved this from New to Needs Info in Triage Jun 1, 2020
@jsuarezruiz jsuarezruiz added s/needs-info ❓ A question has been asked that requires an answer before work can continue on this issue. s/needs-repro ❔ This reported issue doesn't include a sample project reproducing the issue. Please provide one. labels Jun 1, 2020
@haavamoa
Copy link

haavamoa commented Jun 2, 2020

@jsuarezruiz :

Reproduceable project:

https://github.com/haavamoa/GithubIssues/tree/master/src/CarouselViewObservableCollection

Introduction

I have noticed that this happens if you have the following case:

  • You have a empty newed up ObservableCollection
  • You add a item
  • You remove the item (it's now empty)
  • You add a item when it's emptied.

GIF

carouselview_obscollection

Steps to reproduce:

  1. Start CarouselViewObservableCollection (Android).
  2. Add an Item with the "Add Item" button.
  3. Remove Item with the "Remove Item" button.
  4. Add an Item with the "Add Item" button.
  5. Observe that it throws : System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

Workaround

Do a check to see if the ObservableCollection is empty when you remove the last item, if it is, you can new the ObservableCollection so it's ready to add later without exceptions.

  • Workaround is commented out here

Information:

Xamarin Forms Version: 4.6.0.800
Android Device: Samsung A70, Android 10.

@jsuarezruiz jsuarezruiz removed s/needs-info ❓ A question has been asked that requires an answer before work can continue on this issue. s/needs-repro ❔ This reported issue doesn't include a sample project reproducing the issue. Please provide one. s/unverified New report that has yet to be verified labels Jun 2, 2020
@jsuarezruiz jsuarezruiz moved this from Needs Info to Needs Estimate in Triage Jun 2, 2020
@haavamoa
Copy link

haavamoa commented Jun 2, 2020

The workaround does not work as you will have to raise property changed when you new that up again, and the moment I do that I get the same exception.

@haavamoa
Copy link

haavamoa commented Jun 4, 2020

Okay, @jsuarezruiz , I've figured out what @wrkettlitz probably ment with the app crashing if he removed an item.

Repruceable steps

If you do the following with the same reproduceable project:

  1. Click add until you have more than one item
  2. Scroll to the last item
  3. Press "Remove last item"
  4. Observe that app crashes the same way as I described here

Real life example:

I noticed this in a app today when I implemented a way for the user to rearrange the items in the CarouselView. We have a page with a CarouselView with items. The user can click a button to get to a modal that has the ability to rearrange the ìtems.

Scenario:

If the user was at the last item in the CarouselView and then re-aranged that item the CarouselView threw this exception. I have fixed that by remembering what item he was at, scroll to the first position and then go back to that position after he has rearranged it.

@jsuarezruiz jsuarezruiz self-assigned this Jun 16, 2020
@jsuarezruiz jsuarezruiz moved this from Needs Estimate to Ready For Work in Triage Jun 16, 2020
@jsuarezruiz jsuarezruiz moved this from Backlog to In Progress in CarouselView Jun 16, 2020
@samhouts samhouts added the in-progress This issue has an associated pull request that may resolve it! label Jun 16, 2020
@samhouts samhouts removed this from Ready For Work in Triage Jun 16, 2020
@angelru
Copy link

angelru commented Jun 18, 2020

The same issue, any solution??

@samhouts samhouts added this to In Progress in 4.7.0 Jun 20, 2020
@samhouts samhouts removed this from In Progress in 4.7.0 Jul 8, 2020
@samhouts samhouts added this to In Progress in vCurrent (4.8.0) Jul 30, 2020
@samhouts samhouts removed this from In Progress in vCurrent (4.8.0) Aug 4, 2020
@samhouts samhouts added this to In Progress in vNext+1 (5.0.0) Aug 11, 2020
@samhouts samhouts added this to the 5.0.0 milestone Aug 13, 2020
@bill2004158
Copy link
Contributor

bill2004158 commented Aug 26, 2020

any update about this issue? I got same problem.
my stacktrace is:

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 /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.Collection1[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.ItemsViewController1[TItemsView].UpdateTemplatedCell (Xamarin.Forms.Platform.iOS.TemplatedCell cell, Foundation.NSIndexPath indexPath) [0x00012] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewController.cs:222 at Xamarin.Forms.Platform.iOS.ItemsViewController1[TItemsView].GetCell (UIKit.UICollectionView collectionView, Foundation.NSIndexPath indexPath) [0x00033] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ItemsViewController.cs:86
at (wrapper managed-to-native) ObjCRuntime.Messaging.void_objc_msgSend_IntPtr_IntPtr(intptr,intptr,intptr,intptr)
at UIKit.UICollectionView.PerformBatchUpdates (System.Action updates, UIKit.UICompletionHandler completed) [0x00055] in /LibrarThread started: #42y/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/UIKit/UICollectionView.g.cs:572
at Xamarin.Forms.Platform.iOS.ObservableItemsSource.BatchUpdate (System.Action update) [0x00014] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:312
at Xamarin.Forms.Platform.iOS.ObservableItemsSource.Remove (System.Collections.Specialized.NotifyCollectionChangedEventArgs args) [0x00132] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:200
at Xamarin.Forms.Platform.iOS.ObservableItemsSource.CollectionChanged (System.Collections.Specialized.NotifyCollectionChangedEventArgs args) [0x000c7] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:120
at Xamarin.Forms.Platform.iOS.ObservableItemsSource+<>c__DisplayClass28_0.b__0 () [0x00028] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:104
at Xamarin.Forms.Device+<>c__DisplayClass41_0.g__wrapFunction|0 () [0x0002c] in D:\a\1\s\Xamarin.Forms.Core\Device.cs:154
at Xamarin.Forms.Device+<>c__DisplayClass40_01[T].<InvokeOnMainThreadAsync>b__0 () [0x0002f] in D:\a\1\s\Xamarin.Forms.Core\Device.cs:139 at Xamarin.Forms.Platform.iOS.ObservableItemsSource.CollectionChanged (System.Object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs args) [0x00054] in D:\a\1\s\Xamarin.Forms.Platform.iOS\CollectionView\ObservableItemsSource.cs:104 at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_1 (System.Object state) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1037 at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context (System.Object state) [0x0000d] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:1370 at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00071] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:968 at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:910 at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00021] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:1341 at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00074] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:899 at ObjCRuntime.Runtime.ThreadPoolDispatcher (System.Func1[TResult] callback) [0x00006] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.20.2.2/src/Xamarin.iOS/ObjCRuntime/Runtime.cs:289
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () [0x00009] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:1258

@burrowj
Copy link

burrowj commented Sep 9, 2020

I'm getting this too.

@daspiff
Copy link

daspiff commented Sep 30, 2020

I get this fairly regularly if removing multiple items from the ObservableCollection backing the CarouselView ItemsSource. I even tried deferring the removal of items until they were scrolled to but it still threw this exception.

@al185104
Copy link

al185104 commented Oct 5, 2020

I'm having this same problem on Xamarin Forms 4.8.0.1451.
The provided workaround doesn't work. Hope this gets fixed soon. :(

Right now, what works for me is to not raise a property changed when I remove the last item from the carousel view itemsource, and have a default Label on top of the carousel display to say something like "No Item to Show".

@PawKanarek
Copy link
Contributor

It happens too on XF 4.5.0.725

CarouselView automation moved this from In Progress to Done Oct 29, 2020
vNext+1 (5.0.0) automation moved this from In Progress to Done Oct 29, 2020
rmarinho pushed a commit that referenced this issue Oct 29, 2020
…#10865

* Fix issue removing items in CarouselView

* Added instructions to the core gallery sample

* Apply the same fix using List and groups

* Updated sample

* Added Unit Test

* Fixed crash after removing item
@volcano619
Copy link

Is this fixed in v5.0 ?

@rmarinho
Copy link
Member

@volcano619 should be fixed on pre4

@gclap
Copy link

gclap commented Mar 12, 2021

It seems that as of version 5.0.0.2012 this problem still exists? Whenever I try to remove an item from the carouselview on android I get the argument out of range exception.

@SweetNail
Copy link

As saw the solution for this,i tried to set carouselView.Position = 0 when CarouselView_PropertyChanged and CarouselView_CurrentItemChanged, also do not set EmptyViewProperty here,and it works for me

@alexandresanlim
Copy link

The same for me

Vs. 5.x

List`1[T].get_Item (System.Int32 index)
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Stack traces
List`1[T].get_Item (System.Int32 index)
IList.get_Item (System.Int32 index)
ObservableItemsSource.ElementAt (System.Int32 index)
ObservableItemsSource.GetItem (System.Int32 position)
CarouselViewRenderer.SetCurrentItem (System.Int32 carouselPosition)
CarouselViewRenderer+<>c__DisplayClass36_0.<CollectionItemsSourceChanged>b__0 ()
Thread+RunnableImplementor.Run ()
IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this)
(wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.87(intptr,in

@volcano619
Copy link

@rmarinho still present

@gjschoneveld
Copy link

gjschoneveld commented Oct 7, 2021

I got the same problem. It crashes when you delete the last item if that is visible but somehow it doesn't crash when there is only one item.

I found a working workaround that is not mentioned here. If I want to remove the last item I first move the CarouselView 1 item back and do the deletion after some delay. In code it looks like:

// CarView is my CarouselView
// Items is an ObservableCollection that is assigned to CarView.ItemsSource
// this is one item in Items that tries to deleted itself

int index = Items.IndexOf(this);

if (index == -1)
{
    // somehow this is not found
    return;
}

if (index > 0 && this == Items[^1])
{
    // hack to prevent crash when removing last item
    // see: https://github.com/xamarin/Xamarin.Forms/issues/10865
    CarView.CurrentItem = Items[index - 1];
    await Task.Delay(100);
}

// the actual deletion
Items.RemoveAt(index);

edit:
On iOS I need an even longer delay. 1000 ms seems to work.

@MMieszko
Copy link

Still exists here

@taublast
Copy link

taublast commented Mar 22, 2022

The issue is closed but some people might still have nice crashes while changing ItemsSource on the fly. The crash is happening on ANDROID everytime you change the source being on another tab, then when you get back to the tab with carouselview (using xamarin app shell) the currentitem is used from the previous source, index becomes -1. You have actually several crashes incoming, if you bypass the one from index -1, yout get another one from currentItem not belonging to the new itemssource.
Anyway the fix if below.
Android custom renderer:


public class CarouselViewFixed : CarouselViewRenderer
    {
        protected override void UpdateAdapter()
        {
            if (Carousel.ItemsSource != null)
            {
                if (Carousel.CurrentItem != null && Carousel.ItemsSource.FindIndex(Carousel.CurrentItem) < 0)
                {
                    Carousel.SetValueCore(CarouselView.CurrentItemProperty, null);
                    Carousel.SetValueCore(CarouselView.PositionProperty, -1);
                }
            }
            base.UpdateAdapter();
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs changedProperty)
        {
            if (changedProperty.PropertyName == "Position")
            {
                if (Carousel.Position < 0)
                {
                    Carousel.SetValueCore(CarouselView.PositionProperty, 0);
                    return;
                }
            }
            else
            if (changedProperty.PropertyName == "CurrentItem")
            {
                if (Carousel.CurrentItem == null)
                {
                    return;
                }
            }

            base.OnElementPropertyChanged(sender, changedProperty);
        }

        public CarouselViewFixed(Context context) : base(context)
        {
        }
    }

the extension method used:

public static int FindIndex(this IEnumerable collection, object value)
      {
          if (collection is IList list)
          {
              return list.IndexOf(value);
          }
          var searchIndex = 0;
          foreach (var item in collection)
          {
              if (item == value)
              {
                  return searchIndex;
              }
              ++searchIndex;
          }
          return -1;
      }

@TKwakernaak
Copy link

Hi @taublast, The renderer works like a charm, thanks!

@MMieszko
Copy link

MMieszko commented Apr 9, 2022

For me it is still error.

[AppCenterCrashes] Unhandled Exception from source=AndroidEnvironment
[AppCenterCrashes] System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
[AppCenterCrashes] Parameter name: index
[AppCenterCrashes]   at System.Collections.Generic.List`1[T].get_Item (System.Int32 index) [0x00009] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/Collections/Generic/List.cs:161 
[AppCenterCrashes]   at System.Collections.Generic.List`1[T].System.Collections.IList.get_Item (System.Int32 index) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/Collections/Generic/List.cs:188 
[AppCenterCrashes]   at Xamarin.Forms.Platform.Android.ObservableItemsSource.ElementAt (System.Int32 index) [0x0000f] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\ObservableItemsSource.cs:226 
[AppCenterCrashes]   at Xamarin.Forms.Platform.Android.ObservableItemsSource.GetItem (System.Int32 position) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\ObservableItemsSource.cs:62 
[AppCenterCrashes]   at Xamarin.Forms.Platform.Android.ObservableItemsSource.E04-09 13:23:18.791 E/AppCenterCrashes(23858):   at Xamarin.Forms.Platform.Android.CarouselViewRenderer.SetCurrentItem (System.Int32 carouselPosition) [0x00043] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\CarouselViewRenderer.cs:504 
[AppCenterCrashes]   at Xamarin.Forms.Platform.Android.CarouselViewRenderer+<>c__DisplayClass36_0.<CollectionItemsSourceChanged>b__0 () [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.Android\CollectionView\CarouselViewRenderer.cs:316 
[AppCenterCrashes]   at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/Java.Lang/Thread.cs:36 
[AppCenterCrashes]   at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00008] in /Users/builder/azdo/_work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-31/mcw/Java.Lang.IRunnable.cs:84 
[AppCenterCrashes]   at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.40(intptr,intptr)
**System.ArgumentOutOfRangeException:** 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index'

Basically the erros is in class ObservableItemsSource.cs at method

int AdjustIndexForHeader(int index)
{
    return index - (HasHeader ? 1 : 0);
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
a/carouselview e/2 🕑 2 i/high Completely doesn't work, crashes, or is unusably slow, has no obvious workaround; occurs less often in-progress This issue has an associated pull request that may resolve it! t/bug 🐛
Projects
CarouselView
  
Done
Development

Successfully merging a pull request may close this issue.