Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot modify managed objects outside of a write transaction Realm Android

I am facing problems in updating the realm object. I am having 4 fragments. I am carry forwarding the value from one fragment to the next. There are total 16 fields. 1st fragments contains 4 and so on. First I am saving the object of 4 first four fields with this method:-

public static <T extends RealmObject> void InsertRecordinRealm(final Class<T> clazz, final T passedObject, final Integer integerd) {
    Realm realm = getRealmInstance();
    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            realm.copyToRealmOrUpdate(passedObject);
        }
    });
    realm.close();
}

Now, I am getting the Values from the first fragment to the second fragment by using this method:-

public static <T extends RealmObject> T GetRecordById(Class<T> clazz, Integer id) {
    RealmQuery<T> queryForUsern = getRealmInstance().where(clazz).equalTo("RealmId", 1);
    T recordByid = queryForUsern.findFirst();
    return recordByid;
}

Here I am getting the Object Correctly. But when i am updating the object with the values of Second fragment i am getting this error "Cannot modify managed objects outside of a write transaction"

In Second fragment i am Updating the Object with:-

public static <T extends RealmObject> void UpdateRecordinRealmByID(final T passedObject, final Class<T> clazz, final Integer Id) {
        Realm realm = getRealmInstance();
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {

                RealmQuery<T> queryForUsern = 
                getRealmInstance().where(clazz).equalTo("RealmId", 1);
                T recordByid = queryForUsern.findFirst();
                recordByid = passedObject;
                realm.insertOrUpdate(recordByid);
            }
        });
        realm.close();
    }

Help will be appreciated! Thanks in Advance

like image 223
Tushar Pingale Avatar asked Oct 16 '22 18:10

Tushar Pingale


1 Answers

Well, In my case I was updating the value of the realm object outside of realm.executeTransaction {}, as soon as I moved the code inside this realm.executeTransaction {} the error is gone.

like image 128
Suraj Vaishnav Avatar answered Nov 15 '22 06:11

Suraj Vaishnav