Skip to main content

Introduction to Realm Database in Kotlin Android

Introduction to Realm Database in Kotlin Android

Realm is a mobile database that is designed to be fast, efficient, and easy to use. It is an alternative to SQLite and other traditional databases for Android development. Realm Database provides a simple and intuitive API that allows developers to store and retrieve data in a typesafe manner.

In this tutorial, we will explore the features of Realm Database and learn how to install and use it in a Kotlin Android project.

Features of Realm Database

Realm Database offers several key features that make it a popular choice for Android app developers:

  1. Object-Oriented Model: Realm Database allows you to define your data model using Kotlin or Java classes. It provides support for object relationships, inheritance, and polymorphism, making it easy to represent complex data structures.

  2. Automatic Data Sync: Realm supports realtime data synchronization across devices and platforms. It provides built-in support for conflict resolution and offline-first capabilities.

  3. Fast and Efficient: Realm Database is designed to be fast and efficient, providing better performance compared to traditional databases like SQLite. It uses a zero-copy architecture, which eliminates the need for data serialization and deserialization.

  4. Cross-Platform Compatibility: Realm Database supports multiple platforms, including Android, iOS, and React Native. It provides a consistent API across platforms, making it easier to share database code between different projects.

  5. Encryption and Security: Realm Database provides built-in support for data encryption, ensuring that your app's data is secure. It also supports fine-grained access control, allowing you to define who can read and write data.

Installation

To use Realm Database in your Kotlin Android project, you need to add the necessary dependencies to your project's build.gradle file.

  1. Open your project in Android Studio and locate the build.gradle file for your app module.

  2. Add the following dependencies to the dependencies block:

dependencies {
implementation 'io.realm:realm-android:10.9.0'
}
  1. Sync your project to download the required dependencies.

Usage

Now that you have installed Realm Database in your project, let's explore how to use it to perform basic database operations.

1. Define a Data Model

First, you need to define a data model for the objects you want to store in the database. Create a Kotlin class that extends the RealmObject class provided by Realm.

open class Person(
@PrimaryKey
var id: String = UUID.randomUUID().toString(),
var name: String = "",
var age: Int = 0
) : RealmObject()

In this example, we have defined a Person class with three properties: id, name, and age. The @PrimaryKey annotation marks the id property as the primary key for the object.

2. Initialize Realm

Before you can use Realm Database, you need to initialize it in your application's onCreate method.

class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
Realm.init(this)
}
}

Make sure to update your AndroidManifest.xml file to use the custom application class:

<application
android:name=".MyApplication"
...
</application>

3. Create, Update, and Delete Objects

To create a new object in the database, you can simply create an instance of the data model class and call the realm.executeTransaction method.

val realm = Realm.getDefaultInstance()

realm.executeTransaction { realm ->
val person = realm.createObject(Person::class.java)
person.name = "John Doe"
person.age = 25
}

To update an existing object, you can retrieve it from the database using a query and modify its properties.

val realm = Realm.getDefaultInstance()

realm.executeTransaction { realm ->
val person = realm.where(Person::class.java).equalTo("id", "123").findFirst()
person?.name = "Jane Doe"
}

To delete an object, you can simply call the deleteFromRealm method on the object.

val realm = Realm.getDefaultInstance()

realm.executeTransaction { realm ->
val person = realm.where(Person::class.java).equalTo("id", "123").findFirst()
person?.deleteFromRealm()
}

4. Querying the Database

Realm Database provides a fluent API for querying the database. You can use methods like equalTo, greaterThan, lessThan, etc., to filter the results.

val realm = Realm.getDefaultInstance()

val results = realm.where(Person::class.java)
.equalTo("age", 25)
.findAll()

for (person in results) {
Log.d("RealmExample", "Name: ${person.name}")
}

In this example, we are querying the database to find all Person objects with an age of 25.

5. Realtime Updates

Realm Database supports realtime updates, which means that any changes made to the database are automatically reflected in the UI. You can listen for changes using the addChangeListener method.

val realm = Realm.getDefaultInstance()

val results = realm.where(Person::class.java)
.equalTo("age", 25)
.findAll()

results.addChangeListener { persons ->
for (person in persons) {
Log.d("RealmExample", "Name: ${person.name}")
}
}

In this example, the callback will be called whenever a Person object with an age of 25 is added, modified, or deleted from the database.

More Realm Examples