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

时光怂恿深爱的人放手 提交于 2020-01-02 03:14:25

问题


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?


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/35304125/how-can-i-create-a-realm-database-with-initial-data-for-my-android-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!