Bruno Pardini
Bruno Pardini

Reputation: 55

Realm Backup and Migration to a new version

I am facing an issue that is trying to migrate an old Realm structure to a new one, with a new RealmObject and parameters. The thing is, the app is already in Google Play, so the users already stored specific data in some tables. The goal is to restore the data before deleting the realm database and store it somewhere else. I am on a dilemma on what to do right now.

To try to solve this, I implemented the following on my Application class:

RealmMigration migration = new RealmMigration(){
    @Override
    public void migrate(...){
        if(oldVersion == 0){
            //Get the data from realm and store somewhere else
        }
    }
}

RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
         .schemaVersion(1)
         .migration(migration)
         .deleteRealmIfMigrationNeeded()
         .build();
Realm.setDefaultConfiguration(realmConfiguration);
Realm.getInstance(realmConfiguration);

The problem here is that doing it, the method deleteRealmIfMigrationNeeded() is executed and the migration() is not, then all the data is lost before I can get the data from the database. What I wanted is, when updating the app, a way that I can get the version from the database, compare if it is an old version and store the data from the Realm in a file, and then execute the deleteRealmIfMigrationNeeded() to avoid the RealmMigrationNeededException.

I already looked at the following links:
How to backup Realm DB in Android before deleting the Realm file. Is there any way to restore the backup file?
Realm not auto-deleting database if migration needed
https://github.com/realm/realm-cocoa/issues/3583

Upvotes: 0

Views: 627

Answers (1)

Bruno Pardini
Bruno Pardini

Reputation: 55

I solved the issue by adding the proper RealmSchema in the migrate() method. Something like:

RealmMigration migration = new RealmMigration(){
    @Override
    public void migrate(...){
        final RealmSchema = relam.getSchema();
        if(oldVersion == 0){
            if(!schema.get("Person").getPrimaryKey().equals("codePerson")){
                schema.get("Person")
                    .removePrimaryKey()
                    .addPrimaryKey("codePerson");
            }

            //There are other similar statements here
        }
    }
}

Then I deleted the method deleteRealmIfMigrationNeeded() from the RealmConfiguration.

It solved the RealmMigrationNeededException, so the app is starting correctly.

Upvotes: 1

Related Questions