我是Realm编程的初学者。我编写了代码,我可以在我的Realm Database中插入一些值。现在我想检查Realm表中的项目是否相同。第一次,我按键选择项目,如果存在 - 我删除它,然后我插入新项目。 这是我的代码
private void insertIntoDatabase()
{
mRealm.beginTransaction();
mRealm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<VinScannerHistoryModel> rows =
realm.where(VinScannerHistoryModel.class)
.equalTo("userName",vinScannerModel.getName())
.equalTo("vinNumber",vinNumber.getText().toString())
.findAll();
if(rows!=null)
{
rows.clear();
realm.commitTransaction();
}
}
});
ImagesObject imagesObject = mRealm.createObject(ImagesObject.class);
VinScannerHistoryModel vinScannerHistoryModel = mRealm.createObject(VinScannerHistoryModel.class);
vinScannerHistoryModel.setVinNumber(vinNumber.getText().toString());
vinScannerHistoryModel.setStatus(status);
vinScannerHistoryModel.setManufacturer(manufacturer);
vinScannerHistoryModel.setModel(model);
vinScannerHistoryModel.setYear(year);
vinScannerHistoryModel.setVin(vin);
vinScannerHistoryModel.setTerminal_out_date(terminal_out_date);
if(Global.imagePath!=null && Global.imagePath.size()>0)
{
for (int i = 0; i < Global.imagePath.size(); i++) {
imagesObject.setImageName(Global.imagePath.get(i));
vinScannerHistoryModel.getImagesObjects().add(imagesObject);
}
}
if(checkBox.isChecked())
vinScannerHistoryModel.setKey("1");
else
vinScannerHistoryModel.setKey("0");
vinScannerHistoryModel.setPolygon(polygonAdapter.getItem(spinnerPosition).getId()+"");
vinScannerHistoryModel.setUserName(vinScannerModel.getName());
mRealm.commitTransaction();
}
当我运行我的应用程序时,我会崩溃
java.lang.IllegalStateException: Nested transactions are not allowed. Use commitTransaction() after each beginTransaction().
我不知道什么是错的,我怎么能解决这个问题? P.S 正如我所说,我是初学者Realm编程,在你的选择中,它是一种正确的方法来删除我的数据库中的重复项目 谢谢
答案 0 :(得分:0)
异常文本很清楚,不是吗?您无法在交易中启动交易。
mRealm.beginTransaction();
RealmResults<VinScannerHistoryModel> rows =
realm.where(VinScannerHistoryModel.class)
.equalTo("userName", vinScannerModel.getName())
.equalTo("vinNumber", vinNumber.getText().toString())
.findAll();
if (rows != null) {
rows.clear();
}
....
....
答案 1 :(得分:0)
这是一个正确的答案。我解决了我的自我
RealmResults<VinScannerHistoryModel> results
= mRealm.where(VinScannerHistoryModel.class)
.equalTo("userName",vinScannerModel.getName())
.equalTo("vinNumber",vinNumber.getText().toString())
.findAll();
mRealm.beginTransaction();
if(results!=null)
results.clear();