我目前正在尝试使用for循环删除模型中的特定领域对象,
但是每次我执行deleteFromRealm(i)
时,它都会停止循环,并且我无法再删除其他对象。
我还没有尝试过其他选择。
final Realm realms = Realm.getDefaultInstance();
realms.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<CashCountScoreModel> cashCountScoreModels =
CashCountScoreModel.getAll(realm);
for (int i = 0; i < cashCountScoreModels.size(); i++) {
if (cashCountScoreModels.get(i) != null && cashCountScoreModels.get(i).isCashOnHand) {
Log.d("CheckName : pos -- ", i +"~~" + cashCountScoreModels.get(i).isCashOnHand);
Log.d("CheckName : pos --", i + "~~" + cashCountScoreModels.get(i).employeeName);
cashCountScoreModels.deleteFromRealm(i);
// continue;
}
}
}
});
每当我尝试运行该应用程序并执行此特定代码cashCountScoreModels.deleteFromRealm(i);
时,它都会停止循环。
答案 0 :(得分:0)
不确定所使用的Realm版本。但是从3.0.0开始,Realm集合处于活动状态,因此会立即更新。因此,CashCountScoreModels.size()每次删除后返回的计数都会减少。就您而言,我怀疑您集合中只有2个条目。您可能要改用OrderedRealmCollectionSnapshot
。试用以下代码。
final Realm realms = Realm.getDefaultInstance();
realms.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<CashCountScoreModel> cashCountScoreModels = CashCountScoreModel.getAll(realm);
OrderedRealmCollectionSnapshot snapshot = cashCountScoreModels.createSnapshot();
for (CashCountScoreModel cashCountScoreModel : snapshot) {
if (cashCountScoreModel != null && cashCountScoreModel.isCashOnHand) {
Log.d("CheckName : pos -- ", i +"~~" + cashCountScoreModel.isCashOnHand);
Log.d("CheckName : pos --", i + "~~" + cashCountScoreModel.employeeName);
cashCountScoreModel.deleteFromRealm();
}
}
}
});
在https://realm.io/docs/java/latest/上查找Iterations & snapshots
或https://realm.io/docs/java/3.0.0/api/io/realm/OrderedRealmCollection.html#loops上可用的文档以了解集合和OrderedRealmCollectionSnapshot
中更多的实时更新
答案 1 :(得分:0)
发生这种情况是因为我认为您想从一个执行块中删除多个领域对象。 尝试执行代码下面的代码。
RealmResults<CashCountScoreModel> cashCountScoreModels=realm.where(CashCountScoreModel.class).equalTo(CashCountScoreModel.isCashOnHand,true).findAll();
cashCountScoreModels.deleteAllFromRealm();
答案 2 :(得分:0)
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<CashCountScoreModel> cashCountScoreModels=realm.where(CashCountScoreModel.class).equalTo(CashCountScoreModel.isCashOnHand,true).findAll();
cashCountScoreModels.deleteAllFromRealm();
}
});
@Md。 Nowshad Hasan是正确的。只需在Realm Thread中运行即可。
答案 3 :(得分:0)
您不应在循环内调用deleteFromRealm(i)
,因为它总是会导致崩溃。请改用以下代码:
realms.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
RealmResults<CashCountScoreModel> results = CashCountScoreModel.getAll(realm);
results.where().equalTo("isCashOnHand", true).findAll().deleteAllFromRealm();
}
});