shipping Android app with a .realm file and use it as a default database

会有一股神秘感。 提交于 2019-12-14 03:34:38

问题


i have a default.realm file in my "assets/default.realm" folder, I am not able to make it as a default realm database

realm.getDefaultInstance();
        src= new File("assets/default.realm");
        dst=new File("/data/data/" + context.getPackageName() + "/files/");
        if (!(realm.isEmpty())) {
            Log.v("DB","already there!!");
        } else {
            try {
                copyFile(src,dst);
            } catch (IOException e) {
                Log.v("DB","Wrong Path!");
            }
        }
void copyFile(File src, File dst) throws IOException {
        FileChannel inChannel = new FileInputStream(src).getChannel();
        FileChannel outChannel = new FileOutputStream(dst).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }

but failed to copy please help


回答1:


Instead of manually copy the Realm file, you can add it to your RealmConfiguration: https://realm.io/docs/java/1.1.1/api/io/realm/RealmConfiguration.Builder.html#assetFile-android.content.Context-java.lang.String-

Your Realm file might differ from your classes, and MigrationIsNeeded exception will be thrown. In that case, you will have to write a migration step: https://realm.io/docs/java/latest/#migrations

So you will end up with something like:

RealmMigration migration = new RealmMigration() {
    @Override
    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
        RealmSchema schema = realm.getSchema();
        if (oldVersion == 0) {
            schema.create("Person")
                .addField("name", String.class)
                .addField("age", int.class);
            oldVersion++;
        }
    }
};

RealmConfiguration config = new RealmConfiguration.B‌​uilder(this)
  .name(Realm.DEFAULT_‌​REALM_NAME)
  .migration(migration)
  .assetFile(this,"Def‌​ault.realm")
  .schemaVersion(1)
  .build(); 


来源:https://stackoverflow.com/questions/38975192/shipping-android-app-with-a-realm-file-and-use-it-as-a-default-database

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