ElFrancky February 2016

Android Realm issue with setDefaultConfiguration

I've got a problem with realm and his method setDefaultConfiguration. Indeed, my app is multi user, and I need to switch between several realm configurations.

During the main activity loading, I configure the realm configuration like this:

String bddName = String.format("%s.realm",userID);
            userFolder = new File(getApplicationContext().getFilesDir() + "/" + userID);
            config = new RealmConfiguration.Builder(userFolder)
                .name(bddName)
                .schemaVersion(2)
                .migration(new RealmMigration2())
                .build();
            Realm.setDefaultConfiguration(config);

But, If I try to configure it twice with the same config, Realm send me an error:

Configurations cannot be different if used to open the same file. 

Is it possible to test whether the current configuration is different from the one I want to set? I've tried :

if(!config.equals(Realm.getDefaultInstance().getConfiguration()))

But at the first launch of the Activity, Realm return an error, because no default instance is set.

I'm turning around because it's impossible to test the realm configuration before setting it. Could you help me ? Thank you a lot.

Edit : this solution doesn't work too, i've got the same error, however, the RealmFileName are different:

try{
//first time, Realm is not configure, so It's catched.
//else, it set the default config only if the config is different
if(!config.getRealmFileName().equals(Realm.getDefaultInstance().getConfiguration().getRealmFileName())){
                    Realm.setDefaultConfiguration(config);
                }
            }
            catch (Exception e){
                Realm.setDefaultConfiguration(config);
            }

Answers


Christian Melchior February 2016

The problem is that you are creating two instances of the RealmMigration2 class. If you don't override equals in your class:

RealmMigration migration1 = new RealmMigration2();
RealmMigration migration2 = new RealmMigration2();

migration1.equals(migration2) == false

Which will cause the comparison of RealmConfigurations to fail.

So you should either make your RealmMigration instance a singleton or override hashCode()/equals().

Post Status

Asked in February 2016
Viewed 2,258 times
Voted 14
Answered 1 times

Search




Leave an answer