How to add an object to RealmList in Java? Nullpointerexception error

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.

Upvotes: 0

Views: 1016

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81588

Well, you're creating unmanaged RealmObjects that are essentially vanilla objects right here:

Country country = new Country();

Region region = new Region();

With that in mind, there's no magic here, that list in country.regions was never initialized by anyone :)

So you'd need this:

country.setRegions(new RealmList<Region>());
region.setCities(new RealmList<City>());

You can avoid this manual creation of lists (if I'm right, anyways) if you create managed copies in the Realm immediately using realm.createObject(__.class, primaryKeyValue);.

Like

Country country = realm.createObject(Country.class, i);

Upvotes: 2

Related Questions