我有一个Recyclerview来显示项目列表,我从Realm数据库中获取数据并将其存储在ArrayList中。但是当我尝试为特定位置更新特定的BoxItem时,它会向我显示这样的错误。
FATAL EXCEPTION: main Process: one.thebox.android, PID: 7236
java.lang.IllegalStateException: Changing Realm data can only be done from inside a transaction.
at io.realm.internal.Table.throwImmutable(Table.java:1138)
at io.realm.internal.Table.checkImmutable(Table.java:924)
at io.realm.internal.UncheckedRow.setLong(UncheckedRow.java:195)
at io.realm.BoxItemRealmProxy.realmSet$quantity(BoxItemRealmProxy.java:590)
at one.thebox.android.Models.BoxItem.setQuantity(BoxItem.java:347)
at one.thebox.android.adapter.SearchDetailAdapter$SearchedItemViewHolder.updateQuantityInCart(SearchDetailAdapter.java:870)
at one.thebox.android.adapter.SearchDetailAdapter$SearchedItemViewHolder.access$1900(SearchDetailAdapter.java:492)
at one.thebox.android.adapter.SearchDetailAdapter$SearchedItemViewHolder$7.onClick(SearchDetailAdapter.java:786)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
请在此处找到几个代码 - ArrayList box;
boxItem.setQuantity(quantity);
CartHelper.updateQuantityInCart(boxItem, quantity);
boxItems.get(position).setQuantity(quantity);
notifyItemChanged(position);
这里显示错误,无法修改数组列表中的对象
BoxItem -
public class BoxItem extends RealmObject implements Serializable {
private int quantity;
@PrimaryKey
private String uuid;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
CartHelper-是一个更新Realm数据库中数据的类 -
public static void updateQuantityInCart(final BoxItem boxItem, final int quantity) {
Realm realm = TheBox.getRealm();
realm.beginTransaction();
BoxItem boxItem1 = realm.where(BoxItem.class).equalTo("uuid", boxItem.getUuid()).findFirst();
if (boxItem1 != null) {
boxItem1.setQuantity(quantity);
}
realm.commitTransaction();
}
updateQuantityInCart()
是Adapter类中的一个方法,当我们想要更新recyclerview的任何项时调用它。就像我们想要更新特定项目的数量一样
答案 0 :(得分:0)
看起来您正在尝试修改事务之外的Realm对象,这是不允许的。您应在beginTransaction()
commitTransaction()
和CartHelper.updateQuantityInCart(boxItem, quantity);
// Obtain a Realm instance
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//... add or update objects here ...
realm.commitTransaction();
在后台线程中执行的另一个最佳方法可能是:
realm.executeTransactionAsync