Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...