运行带有.realm文件的Android应用程序,并将其用作默认数据库 [英] shipping Android app with a .realm file and use it as a default database
问题描述
我在 assets / default.realm 文件夹中有一个default.realm文件,我无法将其设为默认领域数据库
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();
}
}
但无法复制请帮助
推荐答案
而不是手动复制Realm文件,您可以将其添加到 RealmConfiguration
:< a href =https://realm.io/docs/java/1.1.1/api/io/realm/RealmConfiguration.Builder.html#assetFile-android.content.Context-java.lang.String- = nofollow> https://realm.io/docs/java/1.1.1/api/io/realm/RealmConfiguration.Builder.html#assetFile-android.content.Context-java.lang.String-
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-
您的Realm文件可能与您的类不同,并且会抛出 MigrationIsNeeded
异常。在这种情况下,您必须编写迁移步骤: https://realm.io/docs / java / latest /#migrations
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.Builder(this)
.name(Realm.DEFAULT_REALM_NAME)
.migration(migration)
.assetFile(this,"Default.realm")
.schemaVersion(1)
.build();
这篇关于运行带有.realm文件的Android应用程序,并将其用作默认数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!