LoginSignup
6
8

More than 5 years have passed since last update.

Android KotlinでRealmを使ってみる

Posted at

Realm

環境

Gradleにお任せなので必要な記述を足してsync now。
Realmは3.1.4が現時点で最新なのですがエラーが解消出来てないので一旦1.1.0で記述しています。

// Projectのbuild.gradle
buildscript {
    ...
    repositories {
        jcenter()
    }
    dependencies {
                ...
        classpath "io.realm:realm-gradle-plugin:1.1.0"
    }
    ...
}
// Appのbuild.gradle(他のapplyが並んでる所、最初のあたり)
apply plugin: 'realm-android'

ライフサイクル

onCreateでインスタンスを取得して使い回し、onDestroyでcloseする。
そのため、Activityのメンバ変数として持ちます。

// 変数宣言
class MainActivity() : AppCompatActivity() {
    var mRealm:Realm? = null
    ...
}
    // インスタンス取得
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        val realmConfig = RealmConfiguration.Builder(baseContext).build()
        val realm = Realm.getInstance(realmConfig)
        mRealm = realm
        ...
        // close
    override fun onDestroy() {
        super.onDestroy()
        mRealm?.close()
    }

Insert

TodoモデルをDBに書き込む。

TodoモデルはRealmObjectを継承して実装。
プレーンなgetter/setterはKotlinでは使いませんので実装しません。

open class Todo(
        open var name: String = "",
        open var status: Int = 0,
) : RealmObject() {}

transactionで括った中で処理を行います。
モデルは普通のnewでは無く、realmインスタンスのcreateObjectにて生成します。
copyToRealmにて書き込みします。

        realm.executeTransaction {
            val todoModel = realm.createObject(Todo::class.java)
            todoModel.name = todo
            todoModel.status = 0
            realm.copyToRealm(todoModel)
        }

Read

Todo全件を取得する。
取得はtransaction不要。

val props: RealmResults<Todo> = realm.where(Todo::class.java).findAll()
6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8