I am an android developer, previous I had been working with ActiveAndroid and DBFlow but now we are interested in implement Realm Database to our new projects. The problem is that I am getting an error when trying to add an object to a RealmList inside our models. The error is a Nullpointerexception.
This is my Country model
public class Country extends RealmObject implements Serializable {
@PrimaryKey
private int id;
private String name;
private RealmList<Region> regions;
public Country() {
}
public Country(int id, String name) {
this.id = id;
this.name = name;
}
getter and setters...
And this is my Region model
public class Region extends RealmObject implements Serializable {
@PrimaryKey
private int id;
private String name;
private int countryId;
public RealmList<City> cities;
public Region() {
}
public Region(int id, String name, int countryId ) {
this.id = id;
this.name = name;
this.countryId = countryId;
}
getter and setters...
The main method where I am trying to save the data is
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
for (int i = 0; i < 10 ; i++){
Country country=new Country();
country.setId(i);
country.setName("testCountryName " + i);
for (int y = 0; y < 3; y++) {
Region region=new Region();
region.setId(y);
region.setName("testRegionName " + y);
realm.copyToRealmOrUpdate(region);
country.regions.add(region);
}
realm.copyToRealmOrUpdate(country);
}
realm.commitTransaction();
Finally, the only way to avoid the Nullpointerexception error is adding = new RealmList<>();
when I am declaring the RealmList in each model.
I don't find this answer at Realm Docs and the samples never say that I need to initialize the RealmList so, for that reason I am looking for a solution here.
Please help me with this issue.