developer033 developer033 - 18 days ago 10
Java Question

Adding initial data in Realm Android

I'm using realm and all looks good until I try to add initial data in my database.

I followed the example in this answer, so in my class, that inherits from

Application
, I have the following:

public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
final Map<String, String> map = new LinkedHashMap();
map.put("Key1", "value1");
map.put("Key2", "value2");
RealmConfiguration config = new RealmConfiguration.Builder().initialData(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
int i = 1;
for (Map.Entry entry : map.entrySet()) {
realm.beginTransaction();
Category c = realm.createObject(Category.class, i++);
c.setName((String) entry.getKey());
c.setDescription("Category #" + entry.getValue());
realm.commitTransaction();
}
realm.close();
}
}).deleteRealmIfMigrationNeeded().name("realm.db").build();
Realm.setDefaultConfiguration(config);
}
}


And I thought this configuration should work, however I'm getting the following error:


java.lang.IllegalStateException: The Realm is already in a write transaction in /path/...


Is there something that I'm missing?

Thanks in advance.

Answer

Remove realm.beginTransaction(), realm.commitTransaction() and realm.close() calls. The public void execute(Realm realm) is a method of Realm.Transaction class and it will handle starting and committing the transaction for you:

RealmConfiguration config = new RealmConfiguration.Builder().initialData(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                int i = 1;
                for (Map.Entry entry : map.entrySet()) {
                    Category c = realm.createObject(Category.class, i++);
                    c.setName((String) entry.getKey());
                    c.setDescription("Category #" + entry.getValue());
                }
            }
        }