所以我正在尝试在我的类中实现一个 Realm 列表,但是,我可以在 Realm.io 找到文档没有说明它是否需要 getter/setter 以及它是否应该看起来像。所以这是我的代码:
public class Novel extends RealmObject {
@PrimaryKey
private static int id;
@Required
private static String name;
//Establish relationship with Novel (single) and Chapter (many)
private RealmList<Chapter> chapters;
public static int getId() {
return id;
}//end getId
public static void setId(int id) {
Novel.id = id;
}//end setId
public static String getName() {
return name;
}//end getName
public static void setName(String name) {
Novel.name = name;
}//end setName
}//end Novel.class
为了在 Realm 数据库中存储对象,所有变量都必须有 getter/setter。但是,由于我使用的是 RealmList
,我该如何正确构造我的 getter/setter?
这是 Android Studio 给我的代码,但它看起来并不正确。
public RealmList<Chapter> getChapters() {
return chapters;
}
public void setChapters(RealmList<Chapter> chapters) {
this.chapters = chapters;
}
getter 看起来不错,但是,setter 对我来说没有意义,因为它如何正确地与 RealmList
一起工作。
tldr:为了在我的自定义对象中正确实现 RealmList
,我的 getter/setter 应该是什么?
最佳答案
RealmList
实现了所有有用的接口(interface):
java.lang.Iterable<E>, java.util.Collection<E>, java.util.List<E>
如果你想添加新的 Chapter
到 Novel
使用类似的代码:
Chapter chapter = realm.copyToRealm(new Chapter());
novel.getChapters().add(chapter);
如果你想用新章节替换所有章节:
RealmList<Chapter> chapters = new RealmList<Chapter>();
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters = realm.copyToRealm(chapters);
novel.setChapters(chapters);
关于java - 如何将 Realm 列表正确地实现到我的自定义对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34781213/