First things first, make sure you followed the official Realm tutorial on how to install it on your Android project.
Here’s how I implemented it on my Android project using Kotlin. After installation, initialize the Realm instance on your Application class or your launcher Activity.
import android.app.Application
import io.realm.Realm
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Realm.init(this)
}
}
Create your Realm object by extending the RealmObject class.
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Message(
@PrimaryKey var id: String = "",
var firstName: String = "",
var lastName: String = "",
var email: String = "",
var password: String = ""
) : RealmObject()
Let’s create our Singleton class where we will encapsulate our Realm configuration and instance.
import io.realm.Realm
import io.realm.RealmConfiguration
object AppDatabase {
var realmInstance: Realm
init {
val realmConfiguration = RealmConfiguration.Builder()
.name("awesome_db")
.schemaVersion(1)
.deleteRealmIfMigrationNeeded()
.allowWritesOnUiThread(true)
.build()
realmInstance = Realm.getInstance(realmConfiguration)
}
}
Take note I declared AppDatabase as a Kotlin Object and not a class. Kotlin Objects are handy for one time use classes or singletons.
Another thing to take notice of is the method allowWritesOnUiThread(), Realm will throw an Exception if you will write or read Realm objects inside Coroutines.
Now, let’s say we will retrieve data from the API and then save it in our Realm database. Here’s how I implemented it.
CoroutineScope(Dispatchers.IO).launch {
// Get data from API
withContext(Dispatchers.Main) {
AppDatabase.realmInstance.executeTransaction {
AppDatabase.realmInstance.copyToRealmOrUpdate(message)
}
}
}
And if we want to retrieve data from Realm
val messageList = AppDatabase.realmInstance.where(Message::class.java).findAll()
Let me know if you have any questions by commenting below.