This Java example code shows how to run or execute a write transaction in Realm database on Android using executeTransaction() or executeTransactionAsync() methods.
If the code in the callback throws an exception, Realm cancels the transaction and rollback. Otherwise, Realm commits the transaction.
— Unlike read operations, write operations in Realm must be wrapped in transactions.
— At the end of a write operation, you can either commit the transaction or cancel it.
1 2 3 4 5 6 7 8 |
Realm realm = Realm.getDefaultInstance(); // Obtain a Realm instance realm.beginTransaction(); // Begin Transaction User user = realm.createObject(User.class); // Create a new object user.setName("Prasanna"); user.setCountry("India"); realm.commitTransaction(); // Commit Transaction OR to discard the changes by cancelling the transaction // realm.cancelTransaction(); // Cancel Transaction |
Transaction Block
Instead of manually keeping track of beginTransaction, commitTransaction, and cancelTransaction, you can use the executeTransaction method, which will automatically handle begin, commit, and cancel if an error happens.
1 2 3 4 5 6 7 |
try (Realm realm = Realm.getDefaultInstance()) { realm.executeTransaction(real -> { User user = realm.createObject(User.class); user.setName("Prasanna"); user.setCountry("India"); }); } |
Asynchronous Transaction
Since transactions are blocked by other transactions, you might want to write on a background thread to avoid blocking the UI thread. By using an asynchronous transaction, Realm will run that transaction on a background thread.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Realm realm = Realm.getDefaultInstance(); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm real) { User user = real.createObject(User.class); user.setName("Prasanna"); user.setCountry("India"); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { // Transaction was a success. } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { // Transaction failed and was automatically canceled. } }); |