保存一个对象的时候报错
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);}