0

enter image description hereI got a null reference exception after I delete any item from the sync realm database . the item is deleted from the database but it throws the exception and craches I don't know why it throws this exception or where is the null object .

but when I delete this line the exception disappears : listView.ItemsSource = Employees;

PS : this exception appeared when I tried to sync the realm database online.

public MainPage()
    {
        InitializeComponent();
        Initialize();
        listView.ItemsSource = Employees;
    }    
private async Task Initialize()
    {
        _realm = await OpenRealm();
        Employees = _realm.All<Employee>();
        Entertainments= _realm.All<Entertainment>();
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Employees)));
    }

void OnDeleteClicked(object sender, EventArgs e)
    {
        try {
            var o = _realm.All<Employee>().FirstOrDefault(c => c.EmpId == 4);
            if (o != null)
                _realm.Write(() => { _realm.Remove(o); });
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Employees)));
        }
        catch (Exception exp)
        {
            string msg = exp.Message;
        }

    }

here is a screenshot of the exception

maria nabil
  • 141
  • 3
  • 9

1 Answers1

0

THIS SOLVED THE EXCEPTION ! Thank youu . but the listview is not auto updated now !

According to your code and description, you want to delete item form realm database, and update Listview. I find you use PropertyChanged to want to update Employees, but it doesn't work, because you delete item from realm database, don't change Employees, so it is not fired PropertyChanged event.

 List<Employee> Employees = new List<Employee>();
    private async Task Initialize()
    {
        _realm = await OpenRealm();
        Employees = _realm.All<Employee>().ToList(); ;
        Entertainments = _realm.All<Entertainment>();

    }
    void OnDeleteClicked(object sender, EventArgs e)
    {
        try
        {
            var o = _realm.All<Employee>().FirstOrDefault(c => c.EmpId == 4);
            if (o != null)
                _realm.Write(() => { _realm.Remove(o); });
            Employees = _realm.All<Employee>().ToList();
            listView.ItemsSource = Employees;
        }
        catch (Exception exp)
        {
            string msg = exp.Message;
        }

    }

Helpful article for you: https://dzone.com/articles/xamarinforms-working-with-realm-database

Cherry Bu - MSFT
  • 10,160
  • 1
  • 10
  • 16