How to Save Object into Realm Database in Kotlin

In this article, we will learn about how to save object into Realm Database in an Android Application. The Realm Mobile Database is an alternative to SQLite and core data and can be used as a cross-platform. It offers advanced features such as encryption, data information, and JSON support. The Realm Database is easy to establish and fast performance.

Save Object into Realm Database

Dependency 

Add dependency in your project level build.gradle file and you can also download a realm-VERSION.jar and you can add it into theapp/libs.

classpath 'io.realm:realm-gradle-plugin:10.3.1'

Then apply the realm-android plugin to the top of the application level build.gradle file.

apply plugin: 'realm-android'

Sync the project’s gradle files.

Initializing the Realm Database

Initializing the Realm Database in Android Application.

Realm.init(this) // context, usually an Activity or Application

Save Object in Realm

Below code shows how to save object in Realm.

val user = User("1","Handy Opnion")
Realm.init(this)
val realm = Realm.getDefaultInstance()
realm.beginTransaction()
realm.copyToRealm(user)
realm.commitTransaction()

User Class

First, you have to create the user class and save the following code inside User.kt file.

open class User(
    var userId: String? = null,
    var name: String? = null
) : RealmObject() {
    override fun toString(): String {
        return "User(userId=$userId, name=$name)"
    }
}

Full Activity Code

In the following code, we have created the class RealmSaveObjectActivity. In the code, we have the Save Object code as shown below.

class RealmSaveObjectActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_realm_save_object)

        saveObjectInRealm()
    }

fun saveObjectInRealm() {
        val user = User("1","Handy Opnion")
        Realm.init(this)
        val realm = Realm.getDefaultInstance()
        realm.beginTransaction()
        realm.copyToRealm(user)
        realm.commitTransaction()
    }

}

That’s it. This is how to Save Object into Realm Database Android using Kotlin.

If you have any questions or suggestions, feel free to ask in the comments section below.

Next Articles

How to Retrieve Data From Realm Database in Kotlin

Please share this post:
Posts created 35

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: