Bill Anderson-Blough
Bill Anderson-Blough

Reputation: 71

How can I create a Realm database with initial data for my android app?

I am trying to create a database for my android application using Realm. I need to have data that is pre-populated when the app is installed. Setting a Realm Migration as part of the RealmConfiguration does not run when the version of the database is 0 (defaults to 0 initially). How can I add data the first time the application is setup?

Upvotes: 7

Views: 5819

Answers (3)

Dhiraj Gupta
Dhiraj Gupta

Reputation: 10514

The initial data transaction setup, as shown by @Benjamin in Realm Java works! I only wish that it was present in Realm Cocoa, as well.

I've created an issue for this, in the Github tracker here, #3877.

Upvotes: 0

Jade
Jade

Reputation: 3244

Realm Java 0.89 introduced a method that allows for specifying a transaction to be run when a Realm database is created for the first time. This method, RealmConfiguration.Builder.initialData(Realm.Transaction transaction), is called as part of setting up the RealmConfiguration Builder.

For example

RealmConfiguration config = new RealmConfiguration.Builder(context)
  .name("myrealm.realm")
  .initialData(new MyInitialDataRealmTransaction()), 
  .build();

Upvotes: 10

Bill Anderson-Blough
Bill Anderson-Blough

Reputation: 71

What I am doing right now that works is to check if this is the first time my app is installed and create a new object.

if (Preferences.freshInstall(getApplicationContext())) {
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        Category inbox = new Category("Inbox", "#445566");
        realm.copyToRealm(inbox);
        realm.commitTransaction();
        Preferences.notNew(getApplicationContext());
    }

There should be a better way to do this using Realm Migrations

Upvotes: 0

Related Questions