AndroidLearner
AndroidLearner

Reputation: 21

Multiple realm db's in one application

I want to add a second Realm db to my application. The first one is being created by unzipping realm file which is already provided in my application. I have set the configuration pointing to this.

How can I add second Realm db? The two db's are independent of each other. I have created SecondRealm class extending realm object.

Have followed the below: Realm: Use one or multiple realms in an app (and one or multiple schemas)

But I am getting:

io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
-Class 'SecondRealm' has been added
 at io.realm.internal.OsSharedRealm.nativeGetSharedRealm(Native Method)
        at io.realm.internal.OsSharedRealm.<init>(OsSharedRealm.java:171)
        at io.realm.internal.OsSharedRealm.getInstance(OsSharedRealm.java:241)
        at io.realm.BaseRealm.<init>(BaseRealm.java:136)
        at io.realm.BaseRealm.<init>(BaseRealm.java:105)
        at io.realm.Realm.<init>(Realm.java:164)
        at io.realm.Realm.createInstance(Realm.java:435)
        at io.realm.RealmCache.doCreateRealmOrGetFromCache(RealmCache.java:342)
        at io.realm.RealmCache.createRealmOrGetFromCache(RealmCache.java:282)
        at io.realm.Realm.getInstance(Realm.java:364)

Upvotes: 0

Views: 1806

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

Realm automatically generates a DefaultRealmModule that contains every class annotated with @RealmClass (so that includes classes that extend RealmObject) within the current module.

If this is not the schema you need, then you need to define your own RealmModule that describes the schema for the given Realm file you want to open, for the given RealmConfigurations.

@RealmModule(library = false, classes=[FirstRealm::class.java])
data class FirstModule(val placeholder: String) { // empty data class for equals/hashcode
    constructor(): this("")
}

@RealmModule(library = false, classes=[SecondRealm::class.java])
data class SecondModule(val placeholder: String) { // empty data class for equals/hashcode
    constructor(): this("")
}

val firstConfig = RealmConfiguration.Builder()
                      .name("first.realm")
                      .modules(FirstModule())
                      .build()

val secondConfig = RealmConfiguration.Builder()
                      .name("second.realm")
                      .modules(SecondModule())
                      .build()

val realm1 = Realm.getInstance(firstConfig)
val realm2 = Realm.getInstance(secondConfig)

Upvotes: 3

Related Questions