2016-09-30 93 views
0

我面臨着一個問題,試圖將一箇舊的Realm結構遷移到一個新的RealmObject和參數。問題是,該應用程序已經在Google Play中,所以用戶已經在特定的表格中存儲了特定的數據。目標是在刪除領域數據庫之前還原數據並將其存儲在別處。我現在正處在一個兩難的問題上。領域備份和遷移到一個新版本

爲了嘗試解決這個問題,我實現了我的應用類中的以下內容:

RealmMigration migration = new RealmMigration(){ 
    @Override 
    public void migrate(...){ 
     if(oldVersion == 0){ 
      //Get the data from realm and store somewhere else 
     } 
    } 
} 

RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this) 
     .schemaVersion(1) 
     .migration(migration) 
     .deleteRealmIfMigrationNeeded() 
     .build(); 
Realm.setDefaultConfiguration(realmConfiguration); 
Realm.getInstance(realmConfiguration); 

這裏的問題是,這樣做,則執行該方法deleteRealmIfMigrationNeeded()和遷移()不是,那麼在我可以從數據庫獲取數據之前,所有的數據都會丟失。我想要的是,在更新應用程序時,我可以從數據庫獲取版本,比較它是否爲舊版本,並將來自Realm的數據存儲在文件中,然後執行deleteRealmIfMigrationNeeded()以避免RealmMigrationNeededException。

我已經看了看下面的鏈接:
How to backup Realm DB in Android before deleting the Realm file. Is there any way to restore the backup file?
Realm not auto-deleting database if migration needed
https://github.com/realm/realm-cocoa/issues/3583

回答

1

我通過在遷移()方法中加入適當的RealmSchema解決的問題。喜歡的東西:

RealmMigration migration = new RealmMigration(){ 
    @Override 
    public void migrate(...){ 
     final RealmSchema = relam.getSchema(); 
     if(oldVersion == 0){ 
      if(!schema.get("Person").getPrimaryKey().equals("codePerson")){ 
       schema.get("Person") 
        .removePrimaryKey() 
        .addPrimaryKey("codePerson"); 
      } 

      //There are other similar statements here 
     } 
    } 
} 

然後我刪除從RealmConfiguration方法deleteRealmIfMigrationNeeded()。

它解決了RealmMigrationNeededException,所以該應用程序正常啓動。