Search code examples
androidcopyrealm

How to deep copy an object in Realm containing a RealmList as a property and not have the RealmList objects referencing the same object


I have 3 Realm Objects

public class Portfolio extends RealmObject {
    @PrimaryKey
    public long id;
    public RealmList<PortfolioCoin> portfolioCoins = new RealmList<>();
}

public class PortfolioCoin extends RealmObject {
    public Coin coin;
    public RealmList<Holdings> holdings = new RealmList<>();
    public int color;
}

public class Holdings extends RealmObject {
    @PrimaryKey
    public long id;
    public double amount;
    public double price;
}

Now i would like my users to be able to duplicate their portfolios. If i create a new portfolio and do this

portfolio.portfolioCoins.addAll(activePortfolio2.portfolioCoins);

Both portfolios are basically referencing the same objects. How do i do a deep copy of the items in the list, remembering that its nested twice. Holdings is nested in PortfolioCoin, and PortfolioCoin is nested in Portfolio.

Do i really have to write nested loops to do this? and itereate over each item and then iterate over each item within each item?


Solution

  • You can try following trick

    portfolio.portfolioCoins.addAll(realm.copyToRealmOrUpdate(realm.copyFromRealm(activePortfolio2.portfolioCoins, 2))); // maybe 3?