Beena Beena - 4 months ago 25
Android Question

Update mutiple rows in table using Realm in Android

I am using Realm to store my values in local database.

My requirement is that i need to change one field

status=1
based on some condition.

I have tried following method to accomplish this task. And it is working fine.

RealmResults<NotificationOrder> notificationOrders=realm
.where(NotificationOrder.class)
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.property_id,ConstantMethod.getPreference(getActivity(),UserDefault.kPropertyId))
.equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.status,0)
.findAll();

for (NotificationOrder order:notificationOrders) {
realm.beginTransaction();
order.setStatus(1);
realm.commitTransaction();
}


Now there may be 1000 of such rows in my local db and using for loop to update single row doesn't seem proper way.

So my question :Is there any way like
MYSQL
Update Queries in Realm by which we can update all rows having status=0 by single statement instead of updating single row one by one ?


Thanks.

Answer

If I know right, the objects in the transaction ought to be managed, so

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
       RealmResults<NotificationOrder> notificationOrders = realm
            .where(NotificationOrder.class)
            .equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.property_id,ConstantMethod.getPreference(getActivity(),UserDefault.kPropertyId))
            .equalTo(RealmConstants.TBL_NOTIFICATION_ORDER.status,0)
            .findAll();
        for(NotificationOrder order : notificationOrders) {
            order.setStatus(1);
        }
    }
});

Should be sufficient.

Comments