RDB를 지원하는 라이브러리
Table 대신 class를 생성하고 attribute에 대응하는 field를 포함시킨다.
field는 필요시 Nullable로 선언한다.
Realm 설치 및 초기화
- Gradle에 패키지를 포함시킨다.
// build.gradle(Project) buildscript { repositories { jcenter() } dependencies { classpath "io.realm:realm-gradle-plugin:10.0.1" } } // build.gradle(module) apply plugin: 'com.android.application' apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'realm-android' // android studio 버전에 따라 아래와 같이 선언하기도 한다. plugins { id 'com.android.application' id 'kotlin-android' id 'kotlin-android-extensions' id 'kotlin-kapt' id 'realm-android' }
- Table 역할을 할 class를 생성한다.
package com.example.myapplication import io.realm.RealmObject open class School: RealmObject() { var name: String? = null var location: String? = null }
- Realm을 초기화 시킨다.conifg를 생성해서 Realm을 추가시킨다.
// Realm 초기화 Realm.init(this@RealmActivity) // configuration 생성. // deleteRealmIfMigrationNeede() // 기존 Realm에 Attribute가 추가 되면서 마이그레이션이 필요할 경우 // Realm을 초기화(테이블삭제) 하도록 설정 // allowWritesOnUiThread(true) // 해당 Realm을 UiThread에서 쓰기가 가능하도록 설정 val config: RealmConfiguration = RealmConfiguration.Builder() .deleteRealmIfMigrationNeeded() .allowWritesOnUiThread(true) .build() Realm.setDefaultConfiguration(config) // Realm 인스턴스 생성 val ream = Realm.getDefaultInstance()
- Realm instance를 꺼내서 사용한다.
Realm 쿼리
인스턴스를 이용 ream.executeTransaction{ } 람다식으로 Transaction을 수행한다.
람다식의 인자인 it을 이용해서 쿼리를 수행한다.
val ream = Realm.getDefaultInstance() // Row 생성 = insert ream.executeTransaction{ with(it.createObject(School::class.java)) { this.name = "서울대" this.location = "서울" } } // select findViewById<Button>(R.id.realm_btn_load).setOnClickListener { ream.executeTransaction { val data = it.where(School::class.java).findFirst() Log.d("data1",data.toString()) } } // delete findViewById<Button>(R.id.realm_btn_delete).setOnClickListener { ream.executeTransaction { it.where(School::class.java).findAll().deleteFromRealm(0) } }
'Android > Android기본' 카테고리의 다른 글
ListView (0) | 2021.11.24 |
---|---|
RecyclerView (0) | 2021.11.24 |
TabLayout, Pager (0) | 2021.11.24 |
SharedPreference (0) | 2021.11.24 |
Async (0) | 2021.04.13 |
Uploaded by Notion2Tistory v1.1.0