sbr1308
sbr1308

Reputation: 57

Android Realm createOrUpdateAllFromJson from server response using custom compound key

I am working with realm to handle data going to & from server.From server data format is:

{
"results":[  
  {  
     "unique_id":"8e54ca69-88cb-47f8-8280-f22b888cd50e",

     "breakdown":[  
        {  
           "entity":4,
           "parent_unique_id":"8e54ca69-88cb-47f8-8280-f22b888cd50e",
           //other data
        }
     ],
   //many other json objects and arrays
  }]}

What is done so far:

I am saving or updating the unique breakdown data locally based on entity and parent_unique_id. I have been searching how to do the same using createOrUpdateAllFromJson() method where breakdown would be updated based on those unique identifiers. I can do the same check by querying on each object,looping through and updating. But with lots of data (even with pagination) it is not computationally efficient and definitely time consuming.

From my search found out realm doesn't have any compound primary key support yet and even if I create custom compound primary key, I would not be able to update data when using createOrUpdateAllFromJson().

My Query

Is there any efficient way to update my breakdown data from json without having to write boiler plate code?

Upvotes: 0

Views: 218

Answers (1)

Christian Melchior
Christian Melchior

Reputation: 20126

If you already have a Json structure, I would just manipulate manipulate that, and parse everything to Realm after. Remember that Realm ignores any JSON properties not defined in your Realm model class:

Something like

// Create compound key
JSONArray arr = getResults();
for (int i = 0; i < arr.length(); i++) {
    JSONObject obj = arr.getJSONObject(i);
    JSONObject breakdown = obj.getJSONArray("breakdown").getJSONObject(0);
    obj.put("id", breakdown.getLong("entity") + "-" + breakdown.getString("parent_unique_id"));
}
realm.createOrUpdateAllFromJSon(arr);

Upvotes: 0

Related Questions