Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Data Type from String to Long in Realm Android using RealmMigration

final RealmObjectSchema customerSchema = schema.get("Customer");
customerSchema.removeField("creditPeriod")
    .addField("creditPeriod", Long.class);

Above is the code i used for realm migration. I have deleted the already existing field which was previously string and then added the same field changing its data type in migration code and also in Pojo.class

like image 502
Ankur Avatar asked Oct 23 '25 21:10

Ankur


1 Answers

Below I just mentioned a example for migrating the field type from String to int using the example mentioned in the comment by @christian-melchior

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++;
        }
        
        ......
        
    }
}

Don't forgot to update the schema version and refer the above migration class instance in the RealmConfiguration instance of realm.

like image 104
Mahendran Sakkarai Avatar answered Oct 26 '25 11:10

Mahendran Sakkarai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!