简体   繁体   中英

How to properly save object that contains RealmList?

I have 2 realm objects: Unit and Subunit. Unit object has a realm list of subunits. I work with single Unit object. Periodically a new Subunit object is created and added to Unit's list, and then I call copyToRealmOrUpdate on my Unit object. However, every time I call copyToRealmOrUpdate, all the Subunits that Unit contains get copied again even if they already exist in database. This causes my database to grow in size quickly. Is there a way to save only last Subunit that was added to list every time I save Unit object? Thanks

Try this code for creating new Subunit instances:

realm.beginTransaction();

Unit unit = realm.where(Unit.class)
                 // write your condition for extracting of Unit object
                 .equalTo("id", unit_id).findFirst();

if(unit == null){
    Log.e(APP_TAG, "Unit " + unit_id + " not found");
    realm.cancelTransaction();
    return;
}

Subunit subunit = realm.createObject(Subunit.class);
// setup subunit fields

unit.getSubunits().add(subunit);

realm.commitTransaction();

Instead of creating Unit object every time your need to get this from realm by particular query and put Subunit instance directly to query object.

  1. Create one Unit -Object and save it with copyToRealmOrUpdate in database.
  2. When you create new Subunit , save him with copyToRealmOrUpdate in database.
  3. Then you can call Unit -Object, that is already saved in database, and with Unit.getSubunits().add(Subunit) you add saved Subunit in database to saved Unit in database.

You don't need save Unit many times in database.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM