我使用realm来存储稍后在ListView中显示的项目。 这些项目有一个删除按钮,如果用户点击该按钮两次,应用程序崩溃,因为领域说该对象不再有效进行操作。是否有一个更优雅的解决方案,而不仅仅是尝试捕获异常并忽略它?
以下是onClick方法的代码:
@Override
public void onClick(View view) {
Toast.makeText(context, "Timer " + timer.getUUID() + " was stopped.", Toast.LENGTH_SHORT).show();
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
RealmResults<Timer> result = realm.where(Timer.class).equalTo("uuid", timer.getUUID()).findAll();
result.deleteAllFromRealm();
realm.commitTransaction();
}
答案 0 :(得分:2)
我意识到由于我已经有了对该对象的引用,我可以使用realms isValid()方法,请参阅我的代码:
@Override
public void onClick(View view) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
if (timer.isValid()) {
Toast.makeText(context, "Timer " + timer.getUUID() + " was stopped.", Toast.LENGTH_SHORT).show();
timer.deleteFromRealm();
}
realm.commitTransaction();
}
我还在RealmObject上找到了deleteFromRealm()方法,我之前因某些原因找不到它..
所以,正确的解决方案应该是:
RealmObject o = someRealmObject;
realm.beginTransaction();
if (o.isValid()) o.deleteFromRealm();
realm.commitTransaction();