Search code examples
androidrealm

Using realm in the main app and a library


I'm trying to use Realm in a library and in the main app and it keeps complaining that the models in the main app are not part of the schema. I've basically implemented everything in a similar manner to the example provided by Realm https://github.com/realm/realm-java/tree/master/examples/moduleExample and I've got exactly the same issue.

Error:

io.realm.exceptions.RealmException: class package.models.User is not part of the schema for this Realm.
at io.realm.internal.RealmProxyMediator.getMissingProxyClassException(RealmProxyMediator.java:241)
at io.realm.RealmModuleMediator.getTableName(RealmModuleMediator.java:107)
at io.realm.RealmSchema.getTable(RealmSchema.java:296)
at io.realm.Realm.checkHasPrimaryKey(Realm.java:1469)
at io.realm.Realm.copyToRealmOrUpdate(Realm.java:902)      

The error is triggered as soon as I try to save something to Realm - i.e. after log in I'm trying to save the user's details and it crashes.

In my application class for the main app I've got this code

   @Override
public void onCreate() {
    super.onCreate();
    this.mPrefs = getSharedPreferences(Constants.SHARED_PREFERENCES, 0);

    instance = this;

    // initialisations
    Realm.init(this);
    config = new AppConfig(mPrefs);

    this.realm = Realm.getInstance(getRealmConfig());
}

public Realm getLibraryRealm(Object module, String name){
    RealmConfiguration config = new RealmConfiguration.Builder()
            .name(name)
            .schemaVersion(1)
            .modules(module)
            .build();
    return Realm.getInstance(config);
}

public RealmConfiguration getRealmConfig(){
    return new RealmConfiguration.Builder()
            .name(getPackageName())
            .schemaVersion(1)
            .modules(new RealmModule())
            .build();
}

Then in the library I try to get a Realm instance as follows:

 AppDataAccessor app = (AppDataAccessor) getApplication();
 Realm realm = app.getRealm(new RealmModule(), Constants.REALM_NAME);

Worth mentioning that AppDataAccessor is an interface which is implemented by my application class.

Also, both the main app and the library have Realm Modules defined as follows:

@io.realm.annotations.RealmModule(library = true, classes = { DataSet.class, Field.class, Form.class })
public class RealmModule {
}

and for the main app:

@io.realm.annotations.RealmModule(classes = {Notification.class, User.class})
public class RealmModule {
}

Any help would be much appreciated, thanks!


Solution

  • I found the problem this morning.

    I was defining a RealmModule for the main app and for the library. It's only necessary for the library.