简体   繁体   中英

Deleting items from a list/ObservableCollection in Xamarin.Forms

I'm building an app to learn basic CRUD commands with SQLite and Xamarin.Forms.

I can successfully delete a listitem from the SQlite database, however I'm getting and error when I try to delete it from the listview as well.

Here is the relevant code behind:

namespace ContactBook
{
    

    public partial class MainPage : ContentPage
    {
        private SQLiteAsyncConnection _connection;
        private ObservableCollection<Contacts> _contacts;
        

        public MainPage()
        {
            InitializeComponent();

            _connection = DependencyService.Get<ISQLiteDb>().GetConnection();
            
        }


        protected override async void OnAppearing()
        {

            //Create table and insert current data
            await _connection.CreateTableAsync<Contacts>();

            var contacts = await _connection.Table<Contacts>().ToListAsync();

            listView.ItemsSource = contacts;

            base.OnAppearing();

        }


        async void MenuItem_Clicked(System.Object sender, System.EventArgs e)
        {
            var deletecontact = (sender as MenuItem).CommandParameter as Contacts;


            if (await DisplayAlert("Deleting Contact", $"Are you sure you want to delete {deletecontact.FullName}?", "Yes", "No"))
            {

                await _connection.DeleteAsync(deletecontact);

                _contacts.Remove(deletecontact);

            }

        }

This is the error message:

System.NullReferenceException: Object reference not set to an instance of an object
  at ContactBook.MainPage.MenuItem_Clicked (System.Object sender, System.EventArgs e) [0x00149] in /Users/mikkel/Projects/ContactBook/ContactBook/MainPage.xaml.cs:66
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>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/14.0.0.0/src/Xamarin.iOS/Foundation/NSAction.cs:178
  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) [0x0000e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/14.0.0.0/src/Xamarin.iOS/UIKit/UIApplication.cs:65
  at ContactBook.iOS.Application.Main (System.String[] args) [0x00001] in /Users/mikkel/Projects/ContactBook/ContactBook.iOS/Main.cs:17

you declare a class level variable _contacts

private ObservableCollection<Contacts> _contacts;

but when you load your data, you are not using it

var contacts = await _connection.Table<Contacts>().ToListAsync();

so it remains null, and when you try to reference it here it throws an exception

_contacts.Remove(deletecontact);

to avoid this, use the class variable when loading your data

_contacts = new ObservableCollection<Contacts>(await _connection.Table<Contacts>().ToListAsync());
listView.ItemsSource = _contacts;

 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM