Wai Yan Phyo Wai Yan Phyo - 4 months ago 35
Android Question

how to loop through strings-arrays and add to realm database?

I have strings-arrays like this.

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


And an Student class for RealmObject.

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;
}
}


I would like to loop through each string-arrays and put each names, majors and years to realm Object(Student).realm.commitTransaction() insert data to one object.I want to insert data as three students to realm database.How can I do that?

Answer

Try this code,

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