我对领域不熟悉。 我试图在领域插入一个对象: 我的模特是:
public class Citizen extends RealmObject implements Serializable {
private static final long serialVersionUID = 1L;
@PrimaryKey
@SerializedName("idCitizen")
private long id;
private String postalSection;
private int localityId;
private int stateId;
private int age;
private String gender;
private Evaluation evaluation;
private User user;
@SerializedName("degree")
private Grade grade;
.... // getters and setters
}
成绩模型:
public class Grade extends RealmObject implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("idDegreeGrade")
private int gradeId;
@SerializedName("gradedsc")
private String grade;
// ... getters and setters
}
这是我尝试插入对象时的操作:
Realm realm = Realm.getInstance(ctx);
realm.beginTransaction();
Citizen citizen = realm.createObject(Citizen.class);
citizen.setAge(age); // This is OK
citizen.setGender(gender); // This is OK
Grade grade = new Grade();
grade.setGradeId(gradeId);
citizen.setGrade(grade); // This generate NPE
事情就是当我调试时,公民和年级都不为空。 我明白了:
java.lang.NullPointerException
at io.realm.CitizenRealmProxy.setGrade(CitizenRealmProxy.java:180)
at com.myapp.action.CreateCitizenTask.onPostExecute(CreateCitizenTask.java:109)
当我尝试设置用户时也会发生这种情况:
citizen.setUser(myuser);
知道为什么???
答案 0 :(得分:0)
必须通过以下方式创建组合对象:
Grade grade = realm.createObject(Grade.class);
而不是:
Grade grade = new Grade()