当前位置: 代码迷 >> 综合 >> Realm使用的相关问题 Changing Realm data can only be done from inside a transaction.
  详细解决方案

Realm使用的相关问题 Changing Realm data can only be done from inside a transaction.

热度:58   发布时间:2023-12-14 07:49:13.0

保存一个对象的时候报错

java.lang.IllegalStateException: Changing Realm data can only be done from inside a transaction.

 

代码:

    public static LocalData getLocalData(String id){Realm realm = Realm.getDefaultInstance();if(realm.isInTransaction()){realm.cancelTransaction();}realm.beginTransaction();LocalData loc = realm.where(LocalData.class).equalTo("id", id).findFirst();realm.commitTransaction();return loc;}

错误原因:

Realm还持有对象的引用

解决 :return realm.copyFromRealm(loc);

    public static LocalData getLocalData(String id){Realm realm = Realm.getDefaultInstance();if(realm.isInTransaction()){realm.cancelTransaction();}realm.beginTransaction();LocalData loc = realm.where(LocalData.class).equalTo("id", id).findFirst();realm.commitTransaction();return realm.copyFromRealm(loc);}

 

  相关解决方案