Skip to content

Instantly share code, notes, and snippets.

@zaki50
Last active August 29, 2015 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaki50/c89dd1dbe01e52acdb4a to your computer and use it in GitHub Desktop.
Save zaki50/c89dd1dbe01e52acdb4a to your computer and use it in GitHub Desktop.
Realm インスタンスを取得するためのユーティリティクラスはこんな感じか? Application#onCreate() で setupDatabase() を呼んで、 Activity/Fragment#onCreate() で getRealm() して onDestroy() で Realm#close()
import android.content.Context;
import java.io.File;
import io.realm.Realm;
import io.realm.RealmMigration;
import io.realm.exceptions.RealmMigrationNeededException;
public class RealmUtils {
Applicati
private static final long SCHEMA_VERSION = 1;
private static final String DATABASE_NAME = "foo.realm";
public static Realm getRealm(Context context) {
return Realm.getInstance(context, DATABASE_NAME);
}
// これを Application#onCreate() から呼ぶ
public static void setupDatabase(Context context) {
final File dbFile = new File(context.getFilesDir(), DATABASE_NAME);
if (dbFile.exists()) {
checkAndUpdateSchema(context);
} else {
setInitialSchemaVersion(context, dbFile);
}
}
private static void checkAndUpdateSchema(Context context) {
try {
Realm.getInstance(context, DATABASE_NAME).close();
} catch (RealmMigrationNeededException e) {
Realm.migrateRealmAtPath(new File(context.getFilesDir(), DATABASE_NAME).getAbsolutePath(),
new MyDatabaseMigration());
}
}
private static void setInitialSchemaVersion(Context context, File dbFile) {
// set initial schema version. see https://github.com/realm/realm-java/issues/886
Realm.getInstance(context, dbFile.getName()).close(); // これを呼ばないとスキーマが作成されない
Realm.migrateRealmAtPath(dbFile.getAbsolutePath(), (realm, version) -> SCHEMA_VERSION);
}
private static class MyDatabaseMigration implements RealmMigration {
@Override
public long execute(Realm realm, long version) {
if (version < 1) {
version = 1;
}
// 必要になったらここに移行処理を記述する
//if (version == 1) {
// // migrate to 2
//
// version++;
//}
return SCHEMA_VERSION;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment