Skip to main content

How to use Realm relationships and link objects in Kotlin

How to use Realm relationships and link objects in Kotlin.

Here's a detailed step-by-step tutorial on how to use Realm relationships and link objects in Kotlin:

Step 1: Set up Realm in your project

Before you can use Realm in your Kotlin project, you need to set it up. Follow these steps to add Realm to your project:

  1. Add the Realm Gradle plugin to your project's build.gradle file:
plugins {
id "realm-android"
}
  1. Add the Realm dependency to your app's build.gradle file:
dependencies {
implementation 'io.realm:realm-android-library:10.7.0'
}
  1. Sync your project to download the Realm files and set up the necessary configurations.

Step 2: Define your Realm objects

In Realm, objects are the building blocks of your database. You need to define your Realm objects before you can establish relationships between them. Here's an example of how to define two Realm objects: Person and Pet:

open class Person : RealmObject() {
@PrimaryKey
var id: String = ""
var name: String = ""
var age: Int = 0
var pets: RealmList<Pet> = RealmList()
}

open class Pet : RealmObject() {
@PrimaryKey
var id: String = ""
var name: String = ""
var type: String = ""
var owner: Person? = null
}

In this example, Person has a one-to-many relationship with Pet, as a person can have multiple pets. The owner property in Pet establishes a many-to-one relationship with Person.

Step 3: Initialize and write to the Realm database

To start using the Realm database, you need to initialize it and open a Realm instance. Here's an example of how to do it:

val realm: Realm = Realm.getDefaultInstance()

Once you have the Realm instance, you can create, update, and delete objects in the database. Here's an example of how to create a person and their pet:

realm.executeTransaction { realm ->
val person = realm.createObject(Person::class.java, UUID.randomUUID().toString())
person.name = "John Doe"
person.age = 30

val pet = realm.createObject(Pet::class.java, UUID.randomUUID().toString())
pet.name = "Fluffy"
pet.type = "Cat"
pet.owner = person

person.pets.add(pet)
}

In this example, we're creating a new Person object and setting its properties. Then, we're creating a new Pet object, setting its properties, and establishing the relationship with the person by setting the owner property. Finally, we're adding the pet to the person's list of pets.

Step 4: Query the Realm database

Now that you have data in your Realm database, you can query it to retrieve objects and their relationships. Here's an example of how to query all people and their pets:

val people: RealmResults<Person> = realm.where(Person::class.java).findAll()

for (person in people) {
println("Person: ${person.name}")
for (pet in person.pets) {
println("Pet: ${pet.name}")
}
}

In this example, we're querying all Person objects using the findAll() method. Then, we're iterating over each person and printing their name and their pets' names.

Step 5: Update and delete objects

You can update and delete objects in the Realm database using transactions. Here's an example of how to update a person's age and delete a pet:

realm.executeTransaction { realm ->
val person: Person? = realm.where(Person::class.java).equalTo("name", "John Doe").findFirst()
person?.age = 31

val pet: Pet? = realm.where(Pet::class.java).equalTo("name", "Fluffy").findFirst()
pet?.deleteFromRealm()
}

In this example, we're using a transaction to update the age of the person with the name "John Doe". We're also using a transaction to delete the pet with the name "Fluffy" from the database.

Step 6: Close the Realm instance

Once you're done with the Realm database, it's important to close the Realm instance to free up resources. Here's how you can close the Realm instance:

realm.close()

Closing the Realm instance ensures that your data is saved and any resources used by Realm are released.

That's it! You've learned how to use Realm relationships and link objects in Kotlin. You can now create complex data models with relationships and perform various operations on the Realm database.