2017-02-07 17 views
1
final RealmObjectSchema customerSchema = schema.get("Customer"); 
customerSchema.removeField("creditPeriod") 
    .addField("creditPeriod", Long.class); 

Выше этого кода я использовал для миграции области. Я удалил уже существующее поле, которое ранее было строкой, а затем добавило одно и то же поле, изменяющее его тип данных в коде миграции, а также в Pojo.classИзменение типа данных из строки в Long в Realm Android с использованием RealmMigration

+1

Не уверен, есть ли вопросы? Но если вы хотите преобразовать тип без потери данных, вы можете найти здесь пример: https://github.com/realm/realm-java/blob/master/examples/migrationExample/src/main/java/io/ realm/examples/realmmigrationexample/model/Migration.java # L131 –

ответ

3

Ниже я упомянул пример переноса типа поля из String в int, используя пример упоминается в комментарии от @ Христианско-Мельхиор

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

     ...... 

     // Modify your check according to your version update. 
     if(oldVersion == 1) { 
      // Below I am going to change the type of field 'id' from 'String' to 'int' 

      // Get Schema of a Particular Class. Change --Testing-- with the respected pojo class name 
      RealmObjectSchema schema = schema.get("Testing"); 

      // Add a new temporary field with the new type which you want to migrate. 'id_tmp' is a temporary integer field. 
      schema.addField("id_tmp", int.class); 

      // Set the previous value to the new temporary field 
      schema.transform(new RealmObjectSchema.Function() { 
       @Override 
       public void apply(DynamicRealmObject obj) { 
        // Implement the functionality to change the type. Below I just transformed a string type to int type by casting the value. Implement your methodology below. 
        String id = obj.getString("id"); 

        obj.setInt("id_tmp", Integer.valueOf(id)); 
       } 
      }); 

      // Remove the existing field 
      schema.removeField("id"); 

      // Rename the temporary field which hold the transformed value to the field name which you insisted to migrate. 
      schema.renameField("id_tmp", "id"); 

      oldVersion++; 
     } 

     ...... 

    } 
} 

не забыл обновить версию схемы и отсылает выше экземпляр класса миграции в RealmConfiguration экземпляре области.

+1

Да, это помогло. Спасибо – Ankur

+0

@ankur, если мой ответ разрешил ваш вопрос, примите ответ, щелкнув галочку ниже раздела точки ответа. –

+1

Сделали это так – Ankur