Android アプリケーションでRealmを操作するには、次の高レベルの一連の手順を使用します。
開きたいRealmの構成を作成します。
構成を使用してRealmを開きます。
終了したら、Realm を閉じてリソースを解放します。
デフォルトのRealm
setDefaultConfiguration() メソッドを使用して、任意の RealmConfiguration または SyncConfiguration をアプリケーションのデフォルトとして保存できます。
RealmConfiguration config = new RealmConfiguration.Builder() .name("default-realm") .allowQueriesOnUiThread(true) .allowWritesOnUiThread(true) .compactOnLaunch() .inMemory() .build(); // set this config as the default realm Realm.setDefaultConfiguration(config);
val config = RealmConfiguration.Builder() .name("default-realm") .allowQueriesOnUiThread(true) .allowWritesOnUiThread(true) .compactOnLaunch() .inMemory() .build() // set this config as the default realm Realm.setDefaultConfiguration(config)
次に、 getDefaultConfiguration()を使用してその構成にアクセスするか、 getDefaultInstance() を使用してその構成のRealmを開きます。
Realm realm = Realm.getDefaultInstance(); Log.v("EXAMPLE","Successfully opened the default realm at: " + realm.getPath());
val realm = Realm.getDefaultInstance() Log.v("EXAMPLE","Successfully opened the default realm at: ${realm.path}")
ローカル Realm
ローカル Realm では、クライアント デバイス上にのみデータが保存されます。 RealmConfigurationを使用してローカル Realm の設定をカスタマイズできます。
ローカル Realm の構成
Realm の設定を構成するには、 RealmConfiguration.Builder を使用して RealmConfiguration を作成します。次の例では、以下を使用してローカル Realm を構成します。
ファイル名「alternate-realm」
UI スレッドで明示的に許可された同期読み取り
UI スレッドで明示的に許可された同期書込み (write)
ファイル領域を節約するためにRealmを起動するときに 自動圧縮 します
RealmConfiguration config = new RealmConfiguration.Builder() .name("alternate-realm") .allowQueriesOnUiThread(true) .allowWritesOnUiThread(true) .compactOnLaunch() .build(); Realm realm = Realm.getInstance(config); Log.v("EXAMPLE", "Successfully opened a realm at: " + realm.getPath());
val config = RealmConfiguration.Builder() .name("alternate-realm") .allowQueriesOnUiThread(true) .allowWritesOnUiThread(true) .compactOnLaunch() .build() val realm = Realm.getInstance(config) Log.v("EXAMPLE", "Successfully opened a realm at: ${realm.path}")
重要
UI スレッドでの同期読み取りと書込み
デフォルトでは、非同期トランザクションを使用して、アプリケーションの UI スレッド内の Realm の読み取りまたは書き込みのみが可能です。 つまり、同期メソッドの使用を明示的に許可しない限り、Android アプリケーションのメイン スレッドでは、名前がAsyncという単語で終わるRealmメソッドのみを使用できます。
この制限はアプリケーション ユーザーのメリットのために存在します。UI スレッドで読み取りおよび書込み操作を実行すると、UI のインタラクションが応答しなくなったり低速になったりする可能性があるため、通常、これらの操作は非同期またはバックグラウンド スレッドで取り扱うことをお勧めします。 ただし、アプリケーションで同期 Realm の読み取りまたは UI スレッドでの書込みを使用する必要がある場合は、次のSyncConfigurationオプションを使用して同期メソッドの使用を明示的に許可できます。
SyncConfiguration config = new SyncConfiguration.Builder(app.currentUser(), PARTITION) .allowQueriesOnUiThread(true) .allowWritesOnUiThread(true) .build(); Realm.getInstanceAsync(config, new Realm.Callback() { public void onSuccess(Realm realm) { Log.v( "EXAMPLE", "Successfully opened a realm with reads and writes allowed on the UI thread." ); } });
val config = SyncConfiguration.Builder(app.currentUser(), PARTITION) .allowQueriesOnUiThread(true) .allowWritesOnUiThread(true) .build() Realm.getInstanceAsync(config, object : Realm.Callback() { override fun onSuccess(realm: Realm) { Log.v("EXAMPLE", "Successfully opened a realm with reads and writes allowed on the UI thread.") } })
ローカル Realm を開く
Realm を開くには、 RealmConfiguration.BuilderでRealmConfigurationを作成し、結果のRealmConfigurationをgetInstance()またはgetInstanceAsync() に渡します。
RealmConfiguration config = new RealmConfiguration.Builder() .allowQueriesOnUiThread(true) .allowWritesOnUiThread(true) .build(); Realm realm; try { realm = Realm.getInstance(config); Log.v("EXAMPLE", "Successfully opened a realm at: " + realm.getPath()); } catch (RealmFileException ex) { Log.v("EXAMPLE", "Error opening the realm."); Log.v("EXAMPLE", ex.toString()); }
val config = RealmConfiguration.Builder() .allowQueriesOnUiThread(true) .allowWritesOnUiThread(true) .build() var realm: Realm try { realm = Realm.getInstance(config) Log.v("EXAMPLE", "Successfully opened a realm at: ${realm.path}") } catch(ex: RealmFileException) { Log.v("EXAMPLE", "Error opening the realm.") Log.v("EXAMPLE", ex.toString()) }
読み取り専用邦土
頻繁に変更されない共有データを含む、準備された Realm ファイルをアプリに同梱すると便利な場合があります。 Realm を読み取り専用にするように構成する場合は、 readOnly()メソッドを使用できます。 これにより、Realm への誤った書込みを防止し、書込みが発生した場合に Realm はIllegalStateExceptionをスローします。
警告
読み取り専用の Realm ファイルは書込み可能
読み取り専用Realmは、 プロセスでのみ読み取り専用として強制されます。 Realm ファイル自体は引き続き書込み可能です。
RealmConfiguration config = new RealmConfiguration.Builder() .assetFile("bundled.realm") .readOnly() .modules(new BundledRealmModule()) .build();
val config = RealmConfiguration.Builder() .assetFile("readonly.realm") .readOnly() .modules(BundledRealmModule()) .build()
インメモリ Realm
ファイルに書き込まれず、メモリ内で完全に実行される邦土を作成できます。 Android デバイスのメモリが不足した場合、インメモリ Realm は をメインメモリからディスク領域に一時的にスワップすることがあります。 SDK は、次の場合に、インメモリ邦土によって作成されたすべてのファイルを削除します。
邦土が閉じている
そのRealm へのすべての参照は範囲外です
インメモリ Realm を作成するには、Realm を構成するときにinMemory()を使用します。
RealmConfiguration config = new RealmConfiguration.Builder() .inMemory() .name("java.transient.realm") .build(); Realm realm = Realm.getInstance(config);
val config = RealmConfiguration.Builder() .inMemory() .name("kt.transient.realm") .build() val realm = Realm.getInstance(config)
動的邦土
標準の Realm では、 RealmObjectサブクラスまたはRealmModelインターフェースを使用してスキーマを定義します。 DeviceRealmは実行時に string を使用してスキーマを定義します。 動的 Realm を起動するには、従来の Realm と同じ構成を使用しますが、動的 Realm は構成されたすべてのスキーマ、移行、およびスキーマ バージョンを無視します。
動的Realmは、型の安全性とパフォーマンスを犠牲にして、柔軟性を提供します。 そのため、移行中、手動クライアント リセット、CSV ファイルや JSON などの string ベースのデータを操作する場合など、その柔軟性が必要な場合にのみ 動的Realm を使用します。
可変スキーマを使用して動的 Realm を開くには、 Device Realm を使用します。
RealmConfiguration config = new RealmConfiguration.Builder() .allowWritesOnUiThread(true) .allowQueriesOnUiThread(true) .name("java.dynamic.realm") .build(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config); // all objects in a DynamicRealm are DynamicRealmObjects AtomicReference<DynamicRealmObject> frog = new AtomicReference<>(); dynamicRealm.executeTransaction(transactionDynamicRealm -> { // add type Frog to the schema with name and age fields dynamicRealm.getSchema() .create("Frog") .addField("name", String.class) .addField("age", int.class); frog.set(transactionDynamicRealm.createObject("Frog")); frog.get().set("name", "Wirt Jr."); frog.get().set("age", 42); }); // access all fields in a DynamicRealm using strings String name = frog.get().getString("name"); int age = frog.get().getInt("age"); // because an underlying schema still exists, // accessing a field that does not exist throws an exception try { frog.get().getString("doesn't exist"); } catch (IllegalArgumentException e) { Log.e("EXAMPLE", "That field doesn't exist."); } // Queries still work normally RealmResults<DynamicRealmObject> frogs = dynamicRealm.where("Frog") .equalTo("name", "Wirt Jr.") .findAll();
val config = RealmConfiguration.Builder() .allowWritesOnUiThread(true) .allowQueriesOnUiThread(true) .name("kt.dynamic.realm") .build() val dynamicRealm = DynamicRealm.getInstance(config) // all objects in a DynamicRealm are DynamicRealmObjects var frog: DynamicRealmObject? = null dynamicRealm.executeTransaction { transactionDynamicRealm: DynamicRealm -> // add type Frog to the schema with name and age fields dynamicRealm.schema .create("Frog") .addField("name", String::class.java) .addField("age", Integer::class.java) frog = transactionDynamicRealm.createObject("Frog") frog?.set("name", "Wirt Jr.") frog?.set("age", 42) } // access all fields in a DynamicRealm using strings val name = frog?.getString("name") val age = frog?.getInt("age") // because an underlying schema still exists, // accessing a field that does not exist throws an exception try { frog?.getString("doesn't exist") } catch (e: IllegalArgumentException) { Log.e("EXAMPLE", "That field doesn't exist.") } // Queries still work normally val frogs = dynamicRealm.where("Frog") .equalTo("name", "Wirt Jr.") .findAll()
Realm を閉じる
Realm インスタンスでリソースを解放する場合は、 close()メソッドを呼び出すことが重要です。 を無視して Realm を閉じると、 OutOfMemoryErrorが発生する可能性があります。
realm.close();
realm.close()
Realm スキーマに含めるクラスの設定
Realm モジュールは、Realm オブジェクトモデルのコレクションです。 Realm を開くときに 1 つまたは複数のモジュールを指定して、Realm がスキーマに含めるクラスを制御します。 モジュールを指定しない場合、Realm はアプリケーションで定義されたすべての Realm オブジェクトを含むデフォルトのモジュールを使用します。
注意
Realm を含むライブラリは、 モジュールを通じてスキーマを公開して使用する必要があります。 そうすると、ライブラリがデフォルトのRealmModuleを生成できなくなります。これは、ライブラリを含むすべてのアプリで使用されるデフォルトのRealmModuleと競合します。 ライブラリを使用するアプリは、 モジュールを介してライブラリのクラスにアクセスします。
// A library must create a module and set library = true. This will prevent the default // module from being created. // allClasses = true can be used instead of listing all classes in the library. public class MyLibraryModule {} // ... // Library projects are therefore required to explicitly set their own module. SyncConfiguration libraryConfig = new SyncConfiguration.Builder(app.currentUser(), LIBRARY_PARTITION) .modules(new MyLibraryModule()) .build(); // Apps can add the library RealmModule to their own schema. SyncConfiguration config = new SyncConfiguration.Builder(app.currentUser(), PARTITION) .modules(Realm.getDefaultModule(), new MyLibraryModule()) .build();
// A library must create a module and set library = true. This will prevent the default // module from being created. // allClasses = true can be used instead of listing all classes in the library. class MyLibraryModule // ... // Library projects are therefore required to explicitly set their own module. val libraryConfig = SyncConfiguration.Builder(app.currentUser(), LIBRARY_PARTITION) .modules(MyLibraryModule()) .build() // Apps can add the library RealmModule to their own schema. val config = SyncConfiguration.Builder(app.currentUser(), PARTITION) .modules(Realm.getDefaultModule(), MyLibraryModule()) .build()