简体   繁体   中英

How to avoid Realm rewrite/override child objects?

I have object

public class RProfile extends RealmObject {
    @PrimaryKey
    @Required
    String id;
    String title;
    String description;
}

And another obj

public class RChatMessage extends RealmObject {
        @PrimaryKey
        @Required
        String id;
        String message;
        RProfile sender;
    }
  1. From server I get my profile

    {"id":"131231","title":"My Profile","description","Any description"}

    and write it to Realm:

    public void saveOrUpdateItem(RProfile item) { realm.insertOrUpdate(item); }

  2. After that, from server I get chat message like this:

    {"id":"131231","message":"Any Message","sender":{"id":"131231","title":"My Profile"}}

    and write it to Realm:

    public void saveOrUpdateItem(RChatMessage item) { realm.insertOrUpdate(item); }

But when I'm trying to get RProfile from realm, it doesn't have field description ( description==null ), because when I wrote RChatMessage , the RProfile was override.

How to avoid this behavior?

As stated by you, the first response is of the type "RProfile":

{
  "id": "131231",
  "title": "My Profile",
  "description": "Any description"
}


public void saveOrUpdateItem(RProfile item) {
       realm.insertOrUpdate(item);
}

The second response is of the type "RChatMessage":

{
  "id": "131231",
  "message": "Any Message",
  "sender": {
    "id": "131231",
    "title": "My Profile"
  }
}

Now, if you try to save the data into your local DB using:

public void saveOrUpdateItem(RChatMessage item) {
       realm.insertOrUpdate(item);
}

It will update the data as you have used insertOrUpdatefunction of the realm.

You could follow one of the 2 approaches below:

  1. Use the realm.insert(item) method. It will insert the data and if already found, won't update any value.

  2. Another approach could be to first match and get the description of the RProfile and then add the description from the already saved Model and then execute the insertOrUpdate on the RChatMessage model.

     public void saveOrUpdateItem(RChatMessage item) { RProfile userProfile = realm.where(RProfile.class).equalTo("id", item.getSender().getId()).findFirst(); item.getSender.setDescription(userProfile.getDescription()); realm.insertOrUpdate(item); } 

PS You will need to create the setters and getters accordingly for this code to work properly.

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