최근에 Java에서 Kotlin으로 갈아탔는데, Kotlin으로 Realm을 사용하는 예제가 많지 않아서 포스트를 작성하였다.
Realm을 사용하려면 먼저 Realm library를 초기화해야 한다.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initializes the Realm library and creates a default configuration that is ready to use.
// It is required to call this method before interacting with any other of the Realm API's.
Realm.init(this)
}
}
그리고 그 다음은 model class를 정의한다.
public open class Member: RealmObject() {
@PrimaryKey
public open var id: Int = 0
public open var name: String? = null
public open var age: Int = 0
}
Model class를 정의했으면, 그 다음에는 Model 클래스의 인스턴스를 생성하고, 이를 DB에 저장해본다. Kotlin에서는 closure를 사용할 수 있어서 Java를 사용했을때 보다 훨씬 코드가 깔끔하다. Closure block을 나오면 관련 resources들이 자동적으로 해지되니까 아주 편리하다.
// Executes the given block function on this resource and
// then closes it down correctly whether an exception is thrown or not.
Realm.getDefaultInstance().use { realm ->
// Executes a given transaction on the Realm.
// beginTransaction() and commitTransaction() will be called automatically.
// If any exception is thrown during the transaction
// cancelTransaction() will be called instead of commitTransaction().
realm.executeTransaction {
val member = Member()
member.id = 1
member.name = "Tom"
member.age = 25
realm.copyToRealm(member)
}
}
DB에 데이터를 넣었으니, 이번에는 DB에서 데이터를 가져와본다. 모든 데이터를 가져올 때는 findAll() 함수를 사용한다.
Realm.getDefaultInstance().use { realm ->
realm.where(Member::class.java).findAll().forEach {
Log.d("id", "${it.id}")
Log.d("name", "${it.name}")
Log.d("age", "${it.age}")
}
}
마지막으로, 아래와 같이 검색 조건을 지정하여 특정 데이터만 가져올 수도 있다.
var member: Member? = null
val id = 1
Realm.getDefaultInstance().use { realm ->
val temp = realm.where(Member::class.java).equalTo("id", id).findFirst()
if (temp != null) {
// Makes an unmanaged in-memory copy of an already persisted RealmObject.
// This is a deep copy that will copy all referenced objects.
member = realm.copyFromRealm(temp)
}
}
Log.d("member.id", "${member?.id}")
Log.d("member.name", "${member?.name}")
Log.d("member.age", "${member?.age}")
오늘 포스트는 이것으로 마친다. Kotlin은 Swift와도 많이 비슷해서 배우기도 쉽고, optional이나 closure같은 기능도 지원해서 정말 좋다. 빨리 Kotlin이 큰 인기를 얻어서 Android에서 Java를 대체했으면 좋겠다.


