b.lyte
b.lyte

Reputation: 6737

Storing ArrayList<? extends BaseModel> in Realm

I have an ArrayList<? extends BaseModel> that I'd like to store in Realm.

I have several classes that extend BaseModel and they're all stored in this ArrayList. Will Realm just do the right thing if I store this on disk? Each child class may have it's own additional members and methods.

I should probably just try testing this myself, but I'm away from my dev machine, so thought I'd ask anyway and answer it myself if no one gets to it first.

Thank You!

Upvotes: 0

Views: 488

Answers (2)

ferbeb
ferbeb

Reputation: 163

Realm generates a RealmModuleMediator class that has the following code:

public String getTableName(Class<? extends RealmModel> clazz) {
    checkClass(clazz);

    if (clazz.equals(com.yourpackage.somemodel)) {
        return io.realm.SomeModelRealmProxy.getTableName();
    } else if (clazz.equals(com.yourpackage.anothermodel)) {
        return io.realm.AnotherRealmProxy.getTableName();
    } else if ...

Looks to me like it makes no difference whether you pass in the subclass or the super class.

Upvotes: 0

Sergei Bubenshchikov
Sergei Bubenshchikov

Reputation: 5361

You can store list of BaseModel by call copyToRealmOrUpdate(), if BaseModel extend of RealmObject class or if implement RealmModel interface:

void storeListToRealm(List<? extends BaseModel> models) {
    realm.beginTransaction();
    realm.copyToRealmOrUpdate(models);
    realm.commitTransaction();
}

Otherwise, you need to create "StoreModel", which you can store to realm, and mapping from BaseModel to StoreModel.

Upvotes: 1

Related Questions