How do you use copyToRealmOrUpdate for a list?

Viewed 384

This is some code in my Android App:

public class Offer extends RealmObject {
    @PrimaryKey
    private long id;

}

In my service class:

  RealmList<Offer> currentLocalMerchantOfferList = currentLocalMerchant.getOffers();
   RealmList<Offer> findIncomingMerchantOfferList = findIncomingMerchant.getOffers();
                                if (!EqualsUtil.areEqual(currentLocalMerchantOfferList, findIncomingMerchantOfferList)) {
                                    currentLocalMerchant.setOffers(findIncomingMerchantOfferList == null ? null : realm.copyToRealmOrUpdate(findIncomingMerchantOfferList));
                                }

I get compile error:

error: incompatible types: bad type in conditional expression
                                currentLocalMerchant.setOffers(findIncomingMerchantOfferList == null ? null : realm.copyToRealmOrUpdate(findIncomingMerchantOfferList));

Am I using copyToRealmOrUpdate correctly? If not, how do you use it correctly?

2 Answers

realm.copyToRealmOrUpdate(findIncomingMerchantOfferList) returns a List<T> and not a RealmList<T>.

RealmList represents many-relationship to another object type. Therefore, these randomly inserted objects aren't a many-relationship, therefore they are not RealmList.

In fact, they are internally returned as an ArrayList.

The way you can change your code to accomodate is by:

currentLocalMerchant.getOffers().clear();
currentLocalMerchant.getOffers().addAll(realm.copyToRealmOrUpdate(findIncomingMerchantOfferList));

I think you don't need to use copyToRealmOrUpdate method to set value. Just set the value that you have

 if (!EqualsUtil.areEqual(currentLocalMerchantOfferList, findIncomingMerchantOfferList)) {
                                        currentLocalMerchant.setOffers(findIncomingMerchantOfferList)
                                    }

If findIncomingMerchant.getOffers() back to you persistent data than it will work perfectly.

Related