Wai Yan Phyo Wai Yan Phyo - 1 year ago 117
Android Question

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

I have strings-arrays like this.

<string-array name="names">
<string-array name="majors">
<integer-array name="years">

And an Student class for RealmObject.

public class Student extends RealmObject {

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 Source

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() {
            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();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download