3

I need to model a many-to-many (n:m) relationship with Realm in Android.
E.g., A Country has many Rivers, but there are also Rivers, that flow through many Countries.
I need to query in both directions.

As read here we should avoid these CountryToRiver(int cId, int rId) helper classes known from SQL. Instead Christian suggested to refer bi-directional - sounds good.

Currently I'm getting the data (JSON) and the relationships inside the rivers like this:
getCountries: [{"id":"1", "name":"Dreamland"}, ...]
getRivers: [{"id":"42", "name":"Wateryriver", "length":"5000", "countryIds":[1,2,5]}, ...]

So what I ended up with works, but I'm not sure if it's the best way or if it could be errorprone / easier:

Country.java:

@PrimaryKey
private int id;
private String name;
private RealmList<River> riverRealmList; // not exposed to GSON
// getter & setter

River.java:

@PrimaryKey
private int id;
private String name;
private int length;
@Ignore // ignored by realm
private List<Integer> countryIds;
private RealmList<Country> countryRealmList; // not exposed to GSON
// getter & setter

Main.java:

public void saveData(List<Country> countries, List<River> rivers) { // lists via GSON
  for(Country c : countries) {
    realm.copyToRealmOrUpdate(c); // save countries normally
  }

  for(River r : rivers) {
    buildRelationshipAndSave(r);
  }
}


public void buildRelationshipAndSave(River river) {
  for (int id : river.getCountryIds) {

    // get country with this id from realm and add it to the river's countrylist
    Country realmCountry = realm.where(Country.class).equalTo("id", id).findFirst();
    if(realmCountry!=null)
        river.getContryRealmList().add(realmCountry); //<- is this list access dangerous??

    // until here it was a POJO, now store it in realm
    River realmRiver = realm.copyToRealmOrUpdate(river);

    // now add this river to the country's riverlist, too, if not already existent
    if (!realmCountry.getRiverRealmList().contains(realmRiver))
        realmCountry.getRiverRealmList().add(realmRiver);
  }
}

Do you have any improvements or comments on that?
Thanks in advance!

A2i_
  • 398
  • 3
  • 13
  • What is exactly your problem? – Rohit May 22 '15 at 08:37
  • I want to know if there are problems with this kind of implementation. Like for example a performance issue or something realm specific I didn't think of. I did not find any code like that online, so I'm unsure if I use it the right way. – A2i_ May 22 '15 at 08:40

0 Answers0