Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

"realm migration needed", exception in android while retrieving values from realm db

I am using Realm as a back end in my application. I have created one table named Setting. I added values in that table, by following the steps given on Realm's official site. But when I am going to retrieve values from that table in, I getting exception

"io.realm.exceptions.RealmMigrationNeededException: RealmMigration must be provided" on the line:" realm=Realm.getInstance(getApplicationContext());".

Actually, I am new to android and Realm, so finding trouble to understand what is problem.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT: for new versions of Realm, Realm.init(Context context) is added

Realm.init(context);    
RealmConfiguration config = new RealmConfiguration
                                     .Builder()
                                     .deleteRealmIfMigrationNeeded()
                                     .build();

NOTE: With this config option, any schema change will result in loss of data, specifically:

  • a field is added/removed
  • a new RealmObject class is added
  • an existing RealmObject is removed
  • @Required is added/removed
  • @PrimaryKey is added/removed
  • @Index is added/removed

So it's primarily recommended while the app is in the development stage.


Or add a migration following the official docs:

https://realm.io/docs/java/latest/#migrations

For example,

public class Migration implements RealmMigration {
    @Override
    public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
        RealmSchema schema = realm.getSchema();

        if (oldVersion == 0) {
            RealmObjectSchema personSchema = schema.get("Person");
            personSchema
                .addField("fullName", String.class, FieldAttribute.REQUIRED);
            oldVersion++;
            ... 

  // hash code, equals 

And

Realm.init(context);    
RealmConfiguration config = new RealmConfiguration.Builder() 
                                 .migration(new Migration()) 
                           //      .deleteRealmIfMigrationNeeded()
                                 .build();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...