I am using Realm in my Android apps and I would like to do the following:
- Make an existing field as Primary key.
- Change the type of field from int to String
I wrote the following migration for the above changes:
public class MyMigration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
RealmSchema schema = realm.getSchema();
RealmObjectSchema objectSchema = schema.get("AccessInfo");
objectSchema.addIndex("bookId");
objectSchema.addPrimaryKey("bookId");
objectSchema.removeField("lastOpenedTimeStamp");
objectSchema.addField("lastOpenedTimeStamp", String.class);
oldVersion++;
}
}
However I still face the following error in the MainActivity:
Caused by: io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
- Property 'AccessInfo.bookId' has been made indexed.
- Property 'AccessInfo.lastOpenedTimeStamp' has been changed from 'int' to 'string'.
- Primary Key for class 'AccessInfo' has been added.
The following is my Realm config
defaultConfig = new RealmConfiguration.Builder().modules(new DefaultModule()).migration(new MyMigration()).build();
realm = Realm.getInstance(defaultConfig);
AccessInfo:
public class AccessInfo extends RealmObject {
@PrimaryKey
int bookId;
String lastOpenedTimeStamp;
int lastOpenedPageId;
int lastOpenedPageNumber;
int lastOpenedPartNumber;
int accessCount;
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getLastOpenedTimeStamp() {
return lastOpenedTimeStamp;
}
public void setLastOpenedTimeStamp(String lastOpenedTimeStamp) {
this.lastOpenedTimeStamp = lastOpenedTimeStamp;
}
public int getLastOpenedPageId() {
return lastOpenedPageId;
}
public void setLastOpenedPageId(int lastOpenedPageId) {
this.lastOpenedPageId = lastOpenedPageId;
}
public int getLastOpenedPageNumber() {
return lastOpenedPageNumber;
}
public void setLastOpenedPageNumber(int lastOpenedPageNumber) {
this.lastOpenedPageNumber = lastOpenedPageNumber;
}
public int getLastOpenedPartNumber() {
return lastOpenedPartNumber;
}
public void setLastOpenedPartNumber(int lastOpenedPartNumber) {
this.lastOpenedPartNumber = lastOpenedPartNumber;
}
public int getAccessCount() {
return accessCount;
}
public void setAccessCount(int accessCount) {
this.accessCount = accessCount;
}
}
Appreciate any support. Thanks.