legrojan legrojan - 1 year ago 88
Android Question

Referring to Realm.io FK objects by ID

I'm trying to create a Realm database in Android that mirrors one I have in SQL Server. The idea is to update periodically the one on Android so that both have the same data.

To keep it simple, let's assume I have three tables: Object, Color, Shape. My main table Object has this form:

ID | int
Name | string
IDColor | int
IDShape | int

where IDColor and IDShape refer to the Color and Shape tables. The content of these two is unimportant.

What I would like to do is to define something like this on Android:

public class MyObject extends RealmObject {
private String name;
private Color color;
private Shape shape;

This way I can refer to MyObject.color and MyObject.shape directly. However, this way AFAIK I can't specify color and shape by their ID's, so realm.copyToRealmOrUpdate won't work.

Is there an alternative that allows me to import my JSON directly (ideal) or after some pre- or post-processing?


EDIT: I have found a way to do something akin to this using Xamarin. See my answer below.

Answer Source

Realm is an object database so importing the 3 tables independently doesn't really work in that case. You would need to do some pre-processing that setup the object structure.

You could do it by converting your input-data to JSONObject and use the realm.createOrUpdateFromJsonObject() method. That behaves similar to copyToRealmOrUpdate except it works directly on JSON.


JSONObject obj = new JSONObject(myObjectJson);
obj.put("color", getColorJson(obj.getInt("IDColor")));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download