1. Apply this on project level build.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "io.realm:realm-gradle-plugin:6.0.2"
}
}
2. Apply this on app level build.gradle on very top.
apply plugin: 'com.android.application'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'realm-android'
3. Create a model Person.kt
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Person(
// Properties can be annotated with PrimaryKey or Index.
@PrimaryKey var id: Long = 0,
var name: String = "",
var age: Int = 0,
// Other objects in a one-to-one relation must also subclass RealmObject.
): RealmObject()
4. Create a class which extends Application class. Name it MyApplication.kt
import android.app.Application
import io.realm.Realm
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
// Initialize Realm. Should only be done once when the application starts.
Realm.init(this)
}
}
5. Now take an instance of your Realm object and use in your activity.For example MainActivity.java
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.blogspot.quizappmba.model.Person
import io.realm.Realm
import io.realm.kotlin.createObject
import io.realm.kotlin.where
class MainActivity : AppCompatActivity() {
companion object {
const val TAG: String = "KotlinExampleActivity"
}
private lateinit var realm: Realm
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
realm = Realm.getDefaultInstance()
// All writes must be wrapped in a transaction to facilitate safe multi threading
realm.executeTransaction { realm ->
// Add a person
val person: Person = realm.createObject(0)
person.name = "Young Person"
person.age = 14
}
// Find the first person (no query conditions) and read a field
val person = realm.where<Person>().findFirst()!!
Log.i(TAG, "onCreate: " + person.name)
}
}
Output : I/KotlinExampleActivity: onCreate: Young Person
Comments
Post a Comment