从同步领域数据库删除任何项目后,我得到了空引用异常。 该项目已从数据库中删除,但引发异常并崩溃 我不知道为什么会引发此异常,或者null对象在哪里。
但是当我删除这一行时,异常消失了: listView.ItemsSource =员工;
PS:当我尝试在线同步领域数据库时出现此异常。
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;
}
}
这是该异常的屏幕截图
答案 0 :(得分:0)
这解决了例外!谢谢你 。但是listview现在不会自动更新!
根据您的代码和描述,您想要删除项目表单领域数据库,并更新Listview。我发现您使用PropertyChanged想要更新Employees,但是它不起作用,因为您从领域数据库中删除了项目,请勿更改Employees,因此不会触发PropertyChanged事件。
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;
}
}
对您有用的文章: https://dzone.com/articles/xamarinforms-working-with-realm-database