io.realm.DynamicRealm Java Examples

The following examples show how to use io.realm.DynamicRealm. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserDataRealmMigration.java    From OpenLibre with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
    // During a migration, a DynamicRealm is exposed. A DynamicRealm is an untyped variant of a normal Realm, but
    // with the same object creation and query capabilities.
    // A DynamicRealm uses Strings instead of Class references because the Classes might not even exist or have been
    // renamed.

    // Access the Realm schema in order to create, modify or delete classes and their fields.
    RealmSchema schema = realm.getSchema();

    // Migrate from version 0 to version 1
    if (oldVersion == 0) {

        oldVersion++;
    }

    // Migrate from version 1 to version 2
    if (oldVersion == 1) {
        RealmObjectSchema bloodGlucoseDataSchema = schema.get("BloodGlucoseData");
        bloodGlucoseDataSchema
                .addField("timezoneOffsetInMinutes", int.class)
                .transform(timezoneTransformFunction);

        //oldVersion++;
    }
}
 
Example #2
Source File: MoeQuestApp.java    From MoeQuest with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {

  super.onCreate();
  mAppContext = this;
  // 配置Realm数据库
  RealmConfiguration configuration = new RealmConfiguration
      .Builder(this)
      .deleteRealmIfMigrationNeeded()
      .schemaVersion(6)
      .migration(new RealmMigration() {

        @Override
        public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {

        }
      }).build();

  Realm.setDefaultConfiguration(configuration);

  //配置腾讯bugly
  CrashReport.initCrashReport(getApplicationContext(), ConstantUtil.BUGLY_ID, false);
}
 
Example #3
Source File: AWRealmMigration.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion)
{
    RealmSchema schema = realm.getSchema();
    if (oldVersion == 4)
    {
        RealmObjectSchema realmTicker = schema.get("RealmTokenTicker");
        if (!realmTicker.hasField("currencySymbol")) realmTicker.addField("currencySymbol", String.class);
        oldVersion++;
    }
    //Note: these version updates drop through; eg if oldVersion was 4, then the above code AND this code will execute
    if (oldVersion == 5)
    {
        RealmObjectSchema realmToken = schema.get("RealmToken");
        if (!realmToken.hasField("lastTxTime")) realmToken.addField("lastTxTime", long.class); //add the last transaction update time, used to check tokenscript cached result validity
        oldVersion++;
    }

    //Version 6
    if (oldVersion == 6)
    {
        schema.create("RealmCertificateData")
                .addField("instanceKey", String.class, FieldAttribute.PRIMARY_KEY)
                .addField("result", String.class)
                .addField("subject", String.class)
                .addField("keyName", String.class)
                .addField("keyType", String.class)
                .addField("issuer", String.class)
                .addField("certificateName", String.class)
                .addField("type", int.class);
        oldVersion++;
    }
}
 
Example #4
Source File: HtmlBuilder.java    From realm-browser-android with MIT License 5 votes vote down vote up
public void showTableStructure(DynamicRealm dynamicRealm) {
    RealmObjectSchema realmObjectSchema = dynamicRealm.getSchema().get(simpleTableName);
    Set<String> fieldNames = realmObjectSchema.getFieldNames();
    stringBuilder.append("<div class=\"content\">").append("<table class=\"dataTable\">")
            .append("<th>Column Name</th><th>Type</th>");
    for (String fieldName : fieldNames) {
        RealmFieldType realmFieldType = realmObjectSchema.getFieldType(fieldName);
        stringBuilder.append("<tr>")
                .append("<td>").append(fieldName).append("</td>")
                .append("<td>").append(realmFieldType.name()).append("</td>")
                .append("</tr>");
    }
    stringBuilder.append("</table></div>");
}
 
Example #5
Source File: Migration.java    From talk-android with MIT License 5 votes vote down vote up
@Override
public void migrate(DynamicRealm dynamicRealm, long oldVersion, long newVersion) {
    if (oldVersion == 0) {
        dynamicRealm.getSchema().get("Invitation").addField("email", String.class);
        oldVersion++;
    }
    if (oldVersion == 1) {
        dynamicRealm.getSchema().get("Message").addField("receiptorsStr", String.class);
        dynamicRealm.getSchema().get("Member").addField("service", String.class);
        dynamicRealm.getSchema().create("IdeaDraft")
                .addField("title", String.class)
                .addField("description", String.class);
        dynamicRealm.getSchema().rename("TeamInfo", "Team");
        dynamicRealm.getSchema().get("Team").addField("source", String.class);
        dynamicRealm.getSchema().get("Team").addField("sourceId", String.class);
        dynamicRealm.getSchema().get("Team").addField("signCode", String.class);
        dynamicRealm.getSchema().get("Team").addField("inviteCode", String.class);
        dynamicRealm.getSchema().get("Team").addField("inviteUrl", String.class);
        dynamicRealm.getSchema().get("Team").addField("isQuit", boolean.class);
        dynamicRealm.getSchema().get("Team").addField("nonJoinable", boolean.class);
        dynamicRealm.getSchema().get("Team").addField("hasUnread", boolean.class);
        dynamicRealm.getSchema().get("Team").addField("unread", int.class);
        dynamicRealm.getSchema().get("Team").addPrimaryKey("_id");

        RealmObjectSchema roomSchema = dynamicRealm.getSchema().get("Room");
        dynamicRealm.getSchema().get("Notification").addRealmObjectField("room", roomSchema);
        RealmObjectSchema memberSchema = dynamicRealm.getSchema().get("Member");
        dynamicRealm.getSchema().get("Notification").addRealmObjectField("member", memberSchema);
        RealmObjectSchema storySchema = dynamicRealm.getSchema().get("Story");
        dynamicRealm.getSchema().get("Notification").addRealmObjectField("story", storySchema);

        oldVersion++;
    }
}
 
Example #6
Source File: BlogDBMigration.java    From quill with MIT License 5 votes vote down vote up
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
    RealmSchema schema = realm.getSchema();
    Crashlytics.log(Log.INFO, TAG, "MIGRATING DATABASE from v" + oldVersion + " to v" + newVersion);

    // why < 2? because I forgot to assign a schema version until I wrote this migration, so the
    // oldVersion here will be whatever default is assigned by Realm
    if (oldVersion < 2) {
        if (!schema.get("Post").hasField("customExcerpt")) {
            Crashlytics.log(Log.DEBUG, TAG, "ADDING CUSTOM EXCERPT FIELD TO POST TABLE");
            schema.get("Post").addField("customExcerpt", String.class);
        }
        oldVersion = 2;
    }
}
 
Example #7
Source File: DatabaseManager.java    From Easy_xkcd with Apache License 2.0 5 votes vote down vote up
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
    RealmSchema schema = realm.getSchema();
    RealmObjectSchema objectSchema = schema.get("RealmComic");
    if (!objectSchema.hasField("altText")) { //Add the altText field which wasn't there in the old version!
        objectSchema.addField("altText", String.class);
    }
}
 
Example #8
Source File: GoBeesDbMigration.java    From go-bees with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void migrate(@NonNull DynamicRealm realm, long oldVersion, long newVersion) {
    // No schema changes so far
}
 
Example #9
Source File: Migration.java    From example with Apache License 2.0 4 votes vote down vote up
@Override public void migrate(final DynamicRealm dynamicRealm, long oldVer, long newVer) {
  RealmSchema schema = dynamicRealm.getSchema();
  if (oldVer == 0) {
    Timber.d("migrate(): oldver %d", oldVer);
  }
}
 
Example #10
Source File: RealmBrowser.java    From realm-browser-android with MIT License 4 votes vote down vote up
@Override
public Response serve(IHTTPSession session) {
    Method method = session.getMethod();
    String uri = session.getUri();
    Log.d(TAG, method + " '" + uri + "' ");
    Realm realm = Realm.getDefaultInstance();
    DynamicRealm dynamicRealm = DynamicRealm.getInstance(realm.getConfiguration());
    Set<Class<? extends RealmObject>> modelClasses =
            realm.getConfiguration().getRealmObjectClasses();
    Map<String, String> params = session.getParms();
    String className = params.get("class_name");
    String selectedView = params.get("selected_view");

    HtmlBuilder htmlBuilder = new HtmlBuilder();
    htmlBuilder.start();
    // Sidebar
    htmlBuilder.showSidebar(modelClasses);

    // Main Display
    htmlBuilder.startMainDisplay();
    if (className != null) {
        try {
            Class clazz = Class.forName(className);
            if (RealmObject.class.isAssignableFrom(clazz)) {
                htmlBuilder.setSelectedTableName(clazz);
                htmlBuilder.startMainDisplayNavigation(selectedView);
                if (selectedView != null && selectedView.equals(HtmlBuilder.CONTENT_VIEW)) {
                    String fieldName = params.get("field_name");
                    String queryValue = params.get("query_value");
                    HashMap<String, String> queryMap = new HashMap<>();
                    if (fieldName != null && queryValue != null) {
                        queryMap.put(fieldName, queryValue);
                    }
                    htmlBuilder.showTableContent(dynamicRealm, queryMap);
                } else {
                    htmlBuilder.showTableStructure(dynamicRealm);
                }
                htmlBuilder.closeMainDisplayNavigation();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        htmlBuilder.showEmptyView();
    }
    htmlBuilder.closeMainDisplay();

    realm.close();
    return newFixedLengthResponse(htmlBuilder.finish());
}
 
Example #11
Source File: BlogMetadataDBMigration.java    From quill with MIT License 4 votes vote down vote up
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
    RealmSchema schema = realm.getSchema();
    Crashlytics.log(Log.INFO, TAG, "MIGRATING DATABASE from v" + oldVersion + " to v" + newVersion);

    if (oldVersion == 0) {
        if (schema.get("Post").isNullable("slug")) {
            // get rid of null-valued slugs, if any exist
            RealmResults<DynamicRealmObject> postsWithNullSlug = realm
                    .where(Post.class.getSimpleName())
                    .isNull("slug")
                    .findAll();
            Crashlytics.log(Log.DEBUG, TAG, "CONVERTING " + postsWithNullSlug.size() + " SLUGS FROM NULL TO \"\"");
            for (DynamicRealmObject obj : postsWithNullSlug) {
                obj.setString("slug", "");
            }
            // finally, make the field required
            schema.get("Post").setNullable("slug", false);
        }

        schema.get("Post")
                .setNullable("html", true)
                .setNullable("image", true)
                .setNullable("createdAt", true)
                .setNullable("publishedAt", true)
                .setNullable("metaTitle", true)
                .setNullable("metaDescription", true);
        schema.get("User")
                .addIndex("id")
                .setNullable("image", true)
                .setNullable("bio", true);
        schema.get("Tag")
                .setNullable("slug", true)
                .setNullable("description", true)
                .setNullable("image", true)
                .setNullable("metaTitle", true)
                .setNullable("metaDescription", true)
                .setNullable("createdAt", true)
                .setNullable("updatedAt", true);
        schema.get("Setting")
                .addIndex("id");
        ++oldVersion;
    }

    if (oldVersion == 1) {
        // delete all etags, so the info can be fetched and stored
        // again, with role-based permissions enforced
        RealmResults<DynamicRealmObject> allEtags = realm
                .where(ETag.class.getSimpleName())
                .equalTo("type", ETag.TYPE_CURRENT_USER)
                .or()
                .equalTo("type", ETag.TYPE_ALL_POSTS)
                .findAll();
        Crashlytics.log(Log.DEBUG, TAG, "DELETING ALL ETAGS TO REFRESH DATA COMPLETELY");
        allEtags.deleteAllFromRealm();

        if (!schema.contains("Role")) {
            // create the Role table
            Crashlytics.log(Log.DEBUG, TAG, "CREATING ROLE TABLE");
            schema.create("Role")
                    .addField("id", Integer.class, FieldAttribute.PRIMARY_KEY)
                    .addField("uuid", String.class, FieldAttribute.REQUIRED)
                    .addField("name", String.class, FieldAttribute.REQUIRED)
                    .addField("description", String.class, FieldAttribute.REQUIRED);
        }

        if (!schema.get("User").hasField("roles")) {
            Crashlytics.log(Log.DEBUG, TAG, "ADDING ROLES FIELD TO USER TABLE");
            schema.get("User").addRealmListField("roles", schema.get("Role"));
        }
        ++oldVersion;
    }

    if (oldVersion == 2) {
        if (!schema.get("Post").hasField("conflictState")) {
            Crashlytics.log(Log.DEBUG, TAG, "ADDING CONFLICT STATE FIELD TO POST TABLE");
            schema.get("Post").addField("conflictState", String.class, FieldAttribute.REQUIRED);
        }
        ++oldVersion;
    }

    if (oldVersion == 3) {
        // Ghost 1.0 upgrade, drop all data
        Crashlytics.log(Log.WARN, TAG, "DROPPING ALL DATA");
        final SpectreApplication app = SpectreApplication.getInstance();
        app.setOldRealmSchemaVersion(3);

        // clear logged in state
        AppState.getInstance(app).setBoolean(AppState.Key.LOGGED_IN, false);
        UserPrefs.getInstance(app).clear(UserPrefs.Key.EMAIL);
        UserPrefs.getInstance(app).clear(UserPrefs.Key.PASSWORD);
        UserPrefs.getInstance(app).clear(UserPrefs.Key.PERMALINK_FORMAT);

        ++oldVersion;
    }

    // STARTING FROM V4, THE REALM THAT USED TO STORE THE BLOG DATA NOW
    // ONLY STORES THE *METADATA* FOR ALL CONNECTED BLOGS
}
 
Example #12
Source File: GreenHubDbMigration.java    From batteryhub with Apache License 2.0 4 votes vote down vote up
@Override
public void migrate(@NonNull DynamicRealm realm, long oldVersion, long newVersion) {
    RealmObjectSchema objectSchema;

    // DynamicRealm exposes an editable schema
    RealmSchema schema = realm.getSchema();

    if (schema == null) return;

    try {
        if (oldVersion == 1) {
            objectSchema = schema.get("Sample");
            if (objectSchema != null) {
                objectSchema.addField("version", int.class);
                oldVersion++;
            }
        }

        if (oldVersion == 2) {
            boolean migrated = true;
            objectSchema = schema.get("Device");
            if (objectSchema != null) {
                objectSchema.removeField("serialNumber");
            } else {
                migrated = false;
            }
            objectSchema = schema.get("Sample");
            if (objectSchema != null) {
                objectSchema.addField("mDatabase", int.class);
            } else {
                migrated = false;
            }
            if (migrated) {
                oldVersion++;
            }
        }

        if (oldVersion == 3) {
            objectSchema = schema.get("BatteryDetails");
            if (objectSchema != null) {
                objectSchema.addField("remainingCapacity", int.class);
            }
            oldVersion++;
        }

        if (oldVersion == 4) {
            schema.create("SensorDetails")
                    .addField("fifoMaxEventCount", int.class)
                    .addField("fifoReservedEventCount", int.class)
                    .addField("highestDirectReportRateLevel", int.class)
                    .addField("id", int.class)
                    .addField("isAdditionalInfoSupported", boolean.class)
                    .addField("isDynamicSensor", boolean.class)
                    .addField("isWakeUpSensor", boolean.class)
                    .addField("maxDelay", int.class)
                    .addField("maximumRange", float.class)
                    .addField("minDelay", int.class)
                    .addField("name", String.class)
                    .addField("power", float.class)
                    .addField("reportingMode", int.class)
                    .addField("resolution", float.class)
                    .addField("stringType", String.class)
                    .addField("codeType", int.class)
                    .addField("vendor", String.class)
                    .addField("version", int.class);
            objectSchema = schema.get("SensorDetails");
            schema.get("Sample")
                    .addRealmListField("sensorDetailsList", objectSchema);
            oldVersion++;
        }

        if (oldVersion == 5) {
            objectSchema = schema.get("SensorDetails");
            if (objectSchema != null) {
                objectSchema
                        .addField("frequencyOfUse", int.class)
                        .addField("iniTimestamp", long.class)
                        .addField("endTimestamp", long.class);
            }
            oldVersion++;
        }
    } catch (NullPointerException e) {
        LogUtils.logE(TAG, "Schema is null!");
        e.printStackTrace();
    }
}
 
Example #13
Source File: DbMigrationManager.java    From AcgClub with MIT License 4 votes vote down vote up
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
  for (Entry<Integer, RealmMigration> migration : mMigrattions.entrySet()) {
    migration.getValue().migrate(realm, oldVersion, newVersion);
  }
}
 
Example #14
Source File: StartupActions.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * initialize realm and manage migration
 */
private void realmConfiguration() {
    /**
     * before call RealmConfiguration client need to Realm.init(context);
     */
    Realm.init(context);


    //  new SecureRandom().nextBytes(key);


    // An encrypted Realm file can be opened in Realm Studio by using a Hex encoded version
    // of the key. Copy the key from Logcat, then download the Realm file from the device using
    // the method described here: https://stackoverflow.com/a/28486297/1389357
    // The path is normally `/data/data/io.realm.examples.encryption/files/default.realm`

 /*   RealmConfiguration configuration = new RealmConfiguration.Builder().name("iGapLocalDatabase.realm")
            .schemaVersion(REALM_SCHEMA_VERSION).migration(new RealmMigration()).build();
    DynamicRealm dynamicRealm = DynamicRealm.getInstance(configuration);*/

    Realm configuredRealm = getInstance();
    DynamicRealm dynamicRealm = DynamicRealm.getInstance(configuredRealm.getConfiguration());



    /*if (configuration!=null)
        Realm.deleteRealm(configuration);*/

    /**
     * Returns version of Realm file on disk
     */
    if (dynamicRealm.getVersion() == -1) {
        Realm.setDefaultConfiguration(new RealmConfiguration.Builder().name("iGapLocalDatabaseEncrypted.realm").schemaVersion(REALM_SCHEMA_VERSION).deleteRealmIfMigrationNeeded().build());
        //   Realm.setDefaultConfiguration(configuredRealm.getConfiguration());
    } else {
        Realm.setDefaultConfiguration(configuredRealm.getConfiguration());

    }
    dynamicRealm.close();
    configuredRealm.close();
    try {
        Realm.compactRealm(configuredRealm.getConfiguration());

    } catch (UnsupportedOperationException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: O2RealmMigration.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
        XLog.info("migrate oldVersion:" + oldVersion + ", newVersion:" + newVersion);
        RealmSchema schema = realm.getSchema();
        while (oldVersion< newVersion) {
            if (oldVersion == 9) {
                schema.create("PortalDataRealmObject")
                        .addField("id", String.class, FieldAttribute.PRIMARY_KEY)
                        .addField("name", String.class)
                        .addField("alias", String.class)
                        .addField("description", String.class)
                        .addField("portalCategory", String.class)
                        .addField("firstPage", String.class)
                        .addField("creatorPerson", String.class)
                        .addField("lastUpdateTime", String.class)
                        .addField("lastUpdatePerson", String.class)
                        .addField("createTime", String.class)
                        .addField("updateTime", String.class)
                        .addField("enable", Boolean.class);
                schema.create("NativeAppDataRealmObject")
                        .addField("id", String.class, FieldAttribute.PRIMARY_KEY)
                        .addField("key", String.class)
                        .addField("name", String.class)
                        .addField("enable", Boolean.class);
                oldVersion++;
            }
            if (oldVersion == 10) {
                oldVersion++;
            }
            if (oldVersion == 11) {
//                schema.create("IMUserEntryRealmObject")
//                        .addField("_id", String.class, FieldAttribute.PRIMARY_KEY)
//                        .addField("username", String.class)
//                        .addField("appKey", String.class);
//                schema.create("ImFriendEntryRealmObject")
//                        .addField("_id", String.class, FieldAttribute.PRIMARY_KEY)
//                        .addField("uid", Long.class)
//                        .addField("username", String.class)
//                        .addField("appKey", String.class)
//                        .addField("avatar", String.class)
//                        .addField("displayName", String.class)
//                        .addField("letter", String.class)
//                        .addField("nickName", String.class)
//                        .addField("noteName", String.class)
//                        .addField("user", IMUserEntryRealmObject.class);
//                oldVersion++;
            }
        }

    }
 
Example #16
Source File: Migration.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public void migrate(@NonNull DynamicRealm realm, long oldVersion, long newVersion) {
    RealmSchema schema = realm.getSchema();
}
 
Example #17
Source File: GankMigration.java    From GankApp with GNU General Public License v2.0 2 votes vote down vote up
@Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {

    }