【发布时间】: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<>();。
我在 Realm Docs 上找不到这个答案,并且样本从未说我需要初始化 RealmList,因此我在这里寻找解决方案。
请帮我解决这个问题。
【问题讨论】:
-
您使用的是什么版本的 Realm?我建议 1.2.0
-
嗨,我使用的是 1.2.0。 ->“io.realm:realm-gradle-plugin:1.2.0”
标签: realm