What is the best way to update all records in Realm database table?
Here is what I do at this moment:
My code:
@Override
public void updateAll(final Fragment fragment) {
final long startTime = System.nanoTime();
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
final RealmResults<Stock> realmResults = realm.where(Stock.class).findAll();
Log.d(Constants.LOG_TAG, "All rows [" + realmResults.size() + "] selected and fetched into RealmResults. Called 'execute' callback.");
for (Stock stock : realmResults) {
stock.setDate("1");
stock.setAdjClose(2);
stock.setVolume(3);
stock.setHigh(4);
stock.setLow(5);
stock.setOpen(6);
stock.setClose(7);
}
realm.insertOrUpdate(realmResults);
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.d(Constants.LOG_TAG, "All rows updated. Called 'onSuccess' callback.");
((RealmFragment) fragment).stopBenchmark(startTime, System.nanoTime());
}
});
}
I have also another question:
What do you think about performance of an UPDATE operation compared to SQLite? In my opinion SQLite should be always much faster than Realm (uses POJO) in terms of updating data.
You are on the right track, but a query does not have to be in a transaction, and while you are in a transaction you do not have to insert your updated objects again. The writes in a transaction are automatically updated in realm. That is the point of it.
@Override
public void updateAll(final Fragment fragment) {
final long startTime = System.nanoTime();
final RealmResults<Stock> realmResults = realm.where(Stock.class).findAll();
Log.d(Constants.LOG_TAG, "All rows [" + realmResults.size() + "] selected and fetched into RealmResults. Called 'execute' callback.");
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for (Stock stock : realmResults) {
stock.setDate("1");
stock.setAdjClose(2);
stock.setVolume(3);
stock.setHigh(4);
stock.setLow(5);
stock.setOpen(6);
stock.setClose(7);
}
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.d(Constants.LOG_TAG, "All rows updated. Called 'onSuccess' callback.");
((RealmFragment) fragment).stopBenchmark(startTime, System.nanoTime());
}
});
}
What do you think about performance of an UPDATE operation compared to SQLite? In my opinion SQLite should be always much faster than Realm (uses POJO) in terms of updating data.
This is not a subjective matter. One is faster and one is slower. You can see benchmarks where realm is compared to sqlite in this news post
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.