Java – Add initial data in Realm Android

Add initial data in Realm Android… here is a solution to the problem.

Add initial data in Realm Android

I’m using Realm and everything looks fine until I try to add the initial data to my database.

I followed this > The example in answer, so in my class, which 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);
    }
}

I

think this configuration should work, but I’m getting the following error:

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

Is there anything I’m missing?

Thanks in advance.

Solution

Remove the realm.beginTransaction(), realm.commitTransaction(), and realm.close() calls. public void execute(Realm realm) is a method of the Realm.Transaction class that handles starting and committing transactions 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());
                }
            }
        }

Related Problems and Solutions