我有像这样的字符串数组。
<resources>
<string-array name="names">
<item>foo/item>
<item>bar</item>
<item>moo</item>
</string-array>
<string-array name="majors">
<item>E.P</item>
<item>M.P</item>
<item>E.P</item>
</string-array>
<integer-array name="years">
<item>1968</item>
<item>1993</item>
<item>1995</item>
</integer-array>
</resources>
RealmObject的Student类。
public class Student extends RealmObject {
@PrimaryKey
private int id;
private String name;
private String major;
private Short year;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public Short getYear() {
return year;
}
public void setYear(Short year) {
this.year = year;
}
}
我想循环遍历每个字符串数组,并将每个名称,专业和年份放入领域对象(学生).realm.commitTransaction()将数据插入到一个对象。我想将数据作为三个学生插入到领域数据库我怎么能这样做?
答案 0 :(得分:1)
试试这段代码,
String[] names = getResources().getStringArray(R.array.names);
String[] majors = getResources().getStringArray(R.array.majors);
String[] years = getResources().getStringArray(R.array.years);
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
for(int i=0; i<names.size; i++) {
String name = names[i];
String major = majors[i];
String year = years[i];
short yearValue = Short.valueOf(year);
Student student = new Student();
student.setId(i);
student.setName(name);
student.setYear(yearValue);
realm.insertOrUpdate(student);
}
});