Search code examples
androidrealm

How can I change my code to better suit multiple tables using Realm?


I need some help with Realm.io, I've just been presented to it in a project I'm joining. The former developer showed the source code of our app recently and told me he is using Realm.io just to check if it's the first time the app has been opened by the user. Here is a code snippet of what he is using to do that on the onCreate() method. I'm using Android Studio for development.

  Realm.init(getApplicationContext());
     final Realm realm = Realm.getDefaultInstance();

     final RealmResults<Configuracao> configuracoes =
        realm.where(Configuracao.class)
             .equalTo("chave", "primeiroAcesso")
             .findAll();

The problem is that now I need to insert new data on the database so I've created a class that looks like this:

  public class medicine extends RealmObject {
     @PrimaryKey
     private int id;
     private String med;
     private String doctor;

     /* Setters and getters here */

  }

I'm running into the RealmMigrationNeeded exception, I read the docs and I'm aware that I need to do the migration.

My question is: Where exactly do I put the migration code? Should I put it in the new class file?

Also, in the documentation they tell me that I need to change the version of the schema through something like this:

  RealmConfiguration config1 = new RealmConfiguration.Builder()
            .name("default1.realm")
            .schemaVersion(3)
            .migration(new Migration())
            .build();

But they also say that if that version doesn't exist an exception will be thrown so I'm guessing I need to change the schema before doing that?

Do I have to change anything in the database itself and then call the migration inside the app, or the migration is the process to change the schema? Sorry about the long text but I'm really confused. Thanks for the help in advance.


Solution

  • Yes, you need to create a custom Migration class that must implement RealmMigration. The schema version you provide in the configuration is the version your Realm will have after the migration is run. You can see an example here: https://github.com/realm/realm-java/blob/master/examples/migrationExample/src/main/java/io/realm/examples/realmmigrationexample/model/Migration.java

    In your case it would look something like this:

    public class MyMigration implements RealmMigration {
        @Override
        public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
            RealmSchema schema = realm.getSchema();
    
            if (oldVersion == 2) {
                schema.create("medicine")
                        .addField("id", int.class, FieldAttribute.PRIMARY_KEY)
                        .addField("med", String.class)
                        .addField("doctor", String.class);
    
            }
        }
    }