AndroidにRealm Kotlin SDKを入れて試すための方法をご紹介します。
AndroidStudio Chipmunk 2021.2.1で試しています。
Kotlin SDKのインストール
プロジェクトレベルのGradleに1行追記。
// Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { id 'com.android.application' version '7.2.0' apply false id 'com.android.library' version '7.2.0' apply false id 'org.jetbrains.kotlin.android' version '1.6.21' apply false id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' version '2.0.0' apply false id 'io.realm.kotlin' version '0.11.1' apply false } task clean(type: Delete) { delete rootProject.buildDir }
次にアプリレベルのGradleに3行追記。
plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin' id 'io.realm.kotlin' } : dependencies { implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0-native-mt' implementation 'io.realm.kotlin:library-base:0.11.1' implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.appcompat:appcompat:1.4.2' implementation 'com.google.android.material:material:1.6.1' implementation 'com.google.android.gms:play-services-maps:17.0.1' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'com.google.android.gms:play-services-location:19.0.1' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.3' androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' }
Sync Projectをしてインストール完了。
Realmを操作するサンプルコード
Realmを操作するシンプルなクラスを作ってみました。
package com.atmc118.mapsample import android.util.Log import io.realm.* class CustomApplication{ var realm:Realm //初期化しますよ。 init { val configuration = RealmConfiguration.with(schema = setOf(Task::class)) realm = Realm.open(configuration) } //データを書き込みますよ。 fun write() { realm.writeBlocking { copyToRealm(Task().apply { name = "Do work" status = "Open" }) } } //全てのデータを検索して、表示しますよ。 fun query() { // all tasks in the realm val tasks: RealmResults<Task> = realm.query<Task>().find() for (task in tasks){ Log.d("hoge",task.name) Log.d("hoge",task.status) } } //"Open"になっているタスクの1番目を"In Progree"に変更しますよ。 fun update(){ val openTasks: RealmResults<Task> = realm.query<Task>("status == $0", "Open") .find() realm.writeBlocking { findLatest(openTasks[0])?.status = "In Progress" } } //1番最初のタスクを削除しますよ。 fun delete(){ // delete the first task in the realm realm.writeBlocking { val writeTransactionTasks = query<Task>().find() delete(writeTransactionTasks.first()) } } } class Task : RealmObject { var name: String = "new task" var status: String = "Open" }
参考URL
MongoDBのサイトです。シンプルで分かりやすいです。
https://www.mongodb.com/docs/realm/sdk/kotlin/install/android/#std-label-kotlin-install-android