【问题标题】:How to add an object to RealmList in Java? Nullpointerexception error如何在 Java 中将对象添加到 RealmList?空指针异常错误
【发布时间】:2016-09-07 06:43:30
【问题描述】:

我是一名 android 开发人员,之前我一直在使用 ActiveAndroid 和 DBFlow,但现在我们有兴趣在我们的新项目中实现 Realm 数据库。问题是我在尝试将对象添加到模型中的 RealmList 时遇到错误。错误是 Nullpointerexception

这是我的国家模式

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...

这是我的区域模型

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...

我试图保存数据的主要方法是

        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();

最后,避免 Nullpointerexception 错误的唯一方法是在每个模型中声明 RealmList 时添加 = new RealmList&lt;&gt;();

我在 Realm Docs 上找不到这个答案,并且样本从未说我需要初始化 RealmList,因此我在这里寻找解决方案。

请帮我解决这个问题。

【问题讨论】:

  • 您使用的是什么版本的 Realm?我建议 1.2.0
  • 嗨,我使用的是 1.2.0。 ->“io.realm:realm-gradle-plugin:1.2.0”

标签: realm


【解决方案1】:

好吧,你在这里创建了本质上是普通对象的非托管 RealmObjects:

Country country = new Country();

Region region = new Region();

考虑到这一点,这里没有魔法,country.regions 中的列表从未被任何人初始化:)

所以你需要这个:

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

如果您立即使用realm.createObject(__.class, primaryKeyValue); 在领域中创建托管副本,则可以避免手动创建列表(如果我是对的,无论如何)。

喜欢

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

【讨论】:

  • 感谢@EpicPandaForce,我不知道我可以在 createObject 方法中设置自己的 primaryKeyValue。我会尝试您的解决方案并给您反馈。
  • 从技术上讲,如果不在 createObject() 中对具有 @PrimaryKey 字段的对象设置它,很快就会被弃用 :)
  • 如果我使用这个Country country = realm.createObject(Country.class, i);,我会收到这个错误io.realm.exceptions.RealmPrimaryKeyConstraintException: Value already exists: 0。还需要添加这个country.setRegions(new RealmList&lt;Region&gt;()); region.setCities(new RealmList&lt;City&gt;());?。你能帮帮我吗?
  • 我认为这是因为国家已经存在,主键值为 0
  • 我在数据库中没有值。 :s 我的意思是,是我第一次执行应用程序。
猜你喜欢
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 2011-08-07
相关资源
最近更新 更多