Reputation: 1557
I have following class
public class Student extends RealmObject{
private int studentID;
private String studentName;
// getters and setters here
}
Then I try to set a value to a already created student object
student.setStudentName("Peter");
Then I get following error
java.lang.IllegalStateException: Mutable method call during read transaction.
In order to overcome this I have to do it as follows
Realm realm = Realm.getInstance(this);
realm.beginTransaction();
student.setStudentName("Peter");
realm.commitTransaction();
I don't want to persist this change in the database. How can I just set/change a value to an realm object variable without always persisting it to the database?
Upvotes: 14
Views: 7337
Reputation: 881
You might want to create a new Model. And your new model should implement RealmModel
.
public class StudentRM extends RealmModel{
private int studentID;
private String studentName;
// Constructors here
// getters and setters here
}
Now you can do this.
studentRm.setStudentName("Peter"); //Setting Vale Or
studentRm.addAll(student); //Add all value from DB
studentRm.setStudentName("Jhon"); //It won't change DB anymore
studentRm.getStudentName(); // "Jhon"
Upvotes: 1
Reputation: 81588
If you want to modify the object in a non-persisted manner, you need an unmanaged copy of it.
You can create a copy using realm.copyFromRealm(RealmObject realmObject);
method.
Upvotes: 7
Reputation: 1030
You can use realm.cancelTransaction();
, instead of realm.commitTransaction();
Upvotes: 0
Reputation: 2497
When you are using Realm.createObject()
, the object is added to the Realm and it only works within a write transaction. You can cancel a transaction and thereby discard the object.
Moreover, you can use your model class as a standalone class and create objects in memory (see http://realm.io/docs/java/0.80.0/#creating-objects for details). If you need to persist the objects, you can use the Realm.copyToRealm()
method.
Upvotes: 4