Skip to content

[Android] CollectionView: VirtualView cannot be null here, when clearing and adding items on second navigation #12219

Closed

Description

@jaldinger

Description

An Exception occurs when adding item to ObservableCollection with an EmptyView after having navigated to the same page for a second time.

System.InvalidOperationException: 'VirtualView cannot be null here'

The exception occurs:

  • Only on Android (works fine on Windows)
  • Only when navigating to the page a second (or third...) time
  • I tried using VS 17.4.3, as well as 17.5.0 Preview 2.0, both latest as of today
    maui-android 7.0.52/7.0.100 VS 17.4.33205.214, VS 17.5.33209.295
  • Using both CollectionView EmptyView="something" as well as using separate <CollectionView.EmptyView><ContentView>...

Steps to Reproduce

  1. Create a File > New .NET MAUI App
  2. Add a second ContentPage to the project, named "Page2"
  3. In AppShell.xaml.cs add: Routing.RegisterRoute("Page2", typeof(Page2));
  4. In MauiProgram.cs add: builder.Services.AddScoped<Page2>();
  5. In Page2.xaml remove the Label and replace with:
<CollectionView ItemsSource="{Binding Values}">
            
    <CollectionView.EmptyView>
        <ContentView>
            <Label Text="No items"
                    FontAttributes="Bold" />
        </ContentView>
    </CollectionView.EmptyView>
            
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="x:String">
            <Label Text="{Binding .}" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
            
</CollectionView>

<Button
    Text="Load items"
    Pressed="Button_Pressed" />
  1. In Page2.xaml.cs replace the class with:
public partial class Page2 : ContentPage
{
	public ObservableCollection<string> Values { get; set; } = new();

	public Page2()
	{
		InitializeComponent();

		this.BindingContext = this;
	}

	private async void Button_Pressed(object sender, EventArgs e)
	{
		Values.Clear();

		await Task.Delay(1000);

		for (int i = 1; i <= 5; i++)
			Values.Add($"Item #{i}");
	}
}
  1. In MainPage.xaml.cs modify OnCounterClicked as follows:
private async void OnCounterClicked(object sender, EventArgs e)
{
	count++;

	if (count == 1)
		CounterBtn.Text = $"Clicked {count} time";
	else
		CounterBtn.Text = $"Clicked {count} times";

	SemanticScreenReader.Announce(CounterBtn.Text);

    await Shell.Current.GoToAsync("/Page2");
}
  1. Run the app on Android
  2. Click the button on MainPage
  3. Click the button on Page2 two or more times --> works fine
  4. Go back to MainPage
  5. Click the button on MainPage again
  6. Click the button on Page2 --> Exception occurrs:
System.InvalidOperationException: VirtualView cannot be null here    at Microsoft.Maui.Handlers.ViewHandler`2[[Microsoft.Maui.Controls.ReorderableItemsView, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[AndroidX.RecyclerView.Widget.RecyclerView, Xamarin.AndroidX.RecyclerView, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].get_VirtualView() in D:\a\_work\1\s\src\Core\src\Handlers\View\ViewHandlerOfT.cs:line 42    at Microsoft.Maui.Controls.Handlers.Items.StructuredItemsViewHandler`1[[Microsoft.Maui.Controls.ReorderableItemsView, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].GetItemsLayout() in D:\a\_work\1\s\src\Controls\src\Core\Handlers\Items\StructuredItemsViewHandler.Android.cs:line 10    at Microsoft.Maui.Controls.Handlers.Items.MauiRecyclerView`3[[Microsoft.Maui.Controls.ReorderableItemsView, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Microsoft.Maui.Controls.Handlers.Items.GroupableItemsViewAdapter`2[[Microsoft.Maui.Controls.ReorderableItemsView, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Microsoft.Maui.Controls.Handlers.Items.IGroupableItemsViewSource, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Microsoft.Maui.Controls.Handlers.Items.IGroupableItemsViewSource, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].UpdateLayoutManager() in D:\a\_work\1\s\src\Controls\src\Core\Handlers\Items\Android\MauiRecyclerView.cs:line 288    at Microsoft.Maui.Controls.Handlers.Items.MauiRecyclerView`3[[Microsoft.Maui.Controls.ReorderableItemsView, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Microsoft.Maui.Controls.Handlers.Items.GroupableItemsViewAdapter`2[[Microsoft.Maui.Controls.ReorderableItemsView, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Microsoft.Maui.Controls.Handlers.Items.IGroupableItemsViewSource, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null],[Microsoft.Maui.Controls.Handlers.Items.IGroupableItemsViewSource, Microsoft.Maui.Controls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].UpdateEmptyViewVisibility() in D:\a\_work\1\s\src\Controls\src\Core\Handlers\Items\Android\MauiRecyclerView.cs:line 552    at Microsoft.Maui.Controls.Handlers.Items.DataChangeObserver.OnItemRangeInserted(Int32 positionStart, Int32 itemCount) in D:\a\_work\1\s\src\Controls\src\Core\Handlers\Items\Android\DataChangeObserver.cs:line 53    at AndroidX.RecyclerView.Widget.RecyclerView.AdapterDataObserver.n_OnItemRangeInserted_II(IntPtr jnienv, IntPtr native__this, Int32 positionStart, Int32 itemCount) in C:\a\_work\3\s\generated\androidx.recyclerview.recyclerview\obj\Release\net6.0-android\generated\src\AndroidX.RecyclerView.Widget.RecyclerView.cs:line 1124    at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPII_V(_JniMarshal_PPII_V callback, IntPtr jnienv, IntPtr klazz, Int32 p0, Int32 p1) in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:line 154

Link to public reproduction project repository

https://github.com/jaldinger/MauiAppRepro1.App

Version with bug

7.0

Last version that worked well

Unknown/Other

Affected platforms

Android

Affected platform versions

Android (tested 8.1)

Did you find any workaround?

Removing the EmptyView from the CollectionView avoids the exception (but removes the EmtpyView).

Relevant log output

No response

Activity

  1. added
    t/bug
    on Dec 19, 2022
  2. added
    area-controls-collectionview
    on Dec 19, 2022
  3. canperk commented on Dec 20, 2022

    @canperk

    I solved this problem by adding Task.Delay(50) when adding new item to Collection. This is not the best solutşon but for now it is enough for me

  4. jaldinger commented on Dec 20, 2022

    @jaldinger
    Author

    I solved this problem by adding Task.Delay(50) when adding new item to Collection. This is not the best solutşon but for now it is enough for me

    I tried delays in several places, but it didn't fix anything for me. My code has a delay, but only for demonstration purposes....

  5. added this to the Backlog milestone on Dec 20, 2022
  6. BioTurboNick commented on Dec 25, 2022

    @BioTurboNick
    Contributor

    Just encountered this myself.

  7. lucianparvu commented on Jan 17, 2023

    @lucianparvu

    Same Problem here too

  8. JkPersson commented on Jan 27, 2023

    @JkPersson

    Also seeing it in a CollectionView with no EmptyView!

  9. lucianparvu commented on Jan 27, 2023

    @lucianparvu

    I tried some workarround to replace existing items and now it works ( without clear )

    private void Refresh()
           {
               if (IsBusy) { return; }
              
               Task.Run(async () =>
               {               
                   var ret = await _Service.GetDeliveryAdreses(SearchModel);
                   Application.Current.Dispatcher.Dispatch(() =>
                   {
                       var oldItemsIndexes = ItemList?.Select((item, index) => new { Item = item, Index = index });
                       ret?.Items?.ForEach(p =>
                       {
                           var oldItem = oldItemsIndexes?.FirstOrDefault(i => i.Item.AdressID == p.AdressID);
                           if (oldItem != null)
                           {
                               ItemList[oldItem.Index] = p;
                           }
                           else
                           {
                               ItemList.Add(p);
                           }
                       });
                       IsBusy =   false;   
                        
                   });
               });
           }
    
    
    
  10. jerry08 commented on Jan 27, 2023

    @jerry08

    I experience this issue a lot so I made a workaround using a custom handler. Here's my code:

    using Microsoft.Maui.Controls;
    using Microsoft.Maui.Controls.Handlers.Items;
    using AndroidX.RecyclerView.Widget;
    
    public class CustomCollectionViewHandler : CollectionViewHandler
    {
        private IItemsLayout ItemsLayout { get; set; }
    
        protected override IItemsLayout GetItemsLayout()
        {
            //return base.GetItemsLayout(); //Throws exception
    
            return ItemsLayout;
        }
    
        protected override void ConnectHandler(RecyclerView platformView)
        {
            base.ConnectHandler(platformView);
    
            ItemsLayout = VirtualView.ItemsLayout;
        }
    }
    

    And in MauiProgram.cs, configure the handler

    #if ANDROID
        handlers.AddHandler<CollectionView, CustomCollectionViewHandler>();
    #endif
    

    If you need more workarounds (including this one), I made a small project here.

  11. 7702244 commented on Jan 28, 2023

    @7702244

    @jerry08 Why don't you just send a Pull Request with your workarounds and help the community make MAUI better?

  12. jerry08 commented on Jan 28, 2023

    @jerry08

    @7702244 Pull requests were already submitted for some but were closed since the team is focusing on other matters. That's why I posted some workarounds in the meanwhile.

  13. added
    p/1
    on Feb 3, 2023
  14. 6 remaining items

  15. self-assigned this
    on Feb 16, 2023
  16. moved this to In Progress in MAUI SDK Ongoingon Feb 16, 2023
  17. added a commit that references this issue on Feb 16, 2023
    2a15957
  18. moved this from In Progress to Done in MAUI SDK Ongoingon Feb 16, 2023
  19. added a commit that references this issue on Feb 18, 2023
    445f9a9
  20. added a commit that references this issue on Feb 21, 2023
    a3a2dd2
  21. added
    fixed-in-8.0.0-preview.1.7762
    on Feb 22, 2023
  22. modified the milestones: Backlog, 8.0-preview1 on Feb 22, 2023
  23. LennoxP90 commented on Mar 10, 2023

    @LennoxP90

    I would like to express my hopes this will make it into the next SR for 7.0

  24. ghost locked as resolved and limited conversation to collaborators on Apr 9, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-controls-collectionviewfixed-in-8.0.0-preview.1.7762p/1platform/androidt/bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions