Realm Database on Android: Getting Started

Learn how to use Realm database on Android for data persistence. You’ll learn how to add it to your android app and utilize its features. By Rodrigo Guerrero.

5 (5) · 1 Review

Download materials
Save for later
Share

Realm, a persistence library by MongoDB, lets you easily store objects locally. In this tutorial, you’ll create an app named PetRealm. It uses a Realm database to store information about pets and owners. The app lets the user add pets up for adoption, add owners and show a list of adopted pets. It has the option to adopt a pet by assigning an owner to it.

Over the course of this tutorial, you’ll learn about:

  • Realm database
  • Schema and entities
  • Inserting objects
  • Querying and deleting objects
  • Relationships between entities
  • Realm Studio
  • Comparing Realm and Room
Note: This tutorial assumes you know the basics of Android development. If you’re new to Android development, check out the following tutorials: Beginning Android Development and Kotlin for Android: An Introduction.

Getting Started

Download the materials by clicking the Download Materials button at the top or bottom of this tutorial. Open Android Studio Arctic Fox or later and import the starter project.

Below is a summary of what each package does:

  • common: Contains classes used in different sections of the app.
  • di: You’ll find classes for providing dependency injection here.
  • owners: Contains classes related to owners.
  • pets: Contains classes related to pets.
  • realm: Here, you’ll find all classes related to Realm.

Build and run the app. You’ll see a screen with the bottom navigation bar, a button to add pets and a spinner at the top.

Pets to adopt empty screen

Press the button and you’ll see the screen to add pets, as shown below:

Add pets screen

Dismiss the screen and press the Adopted pets option in the navigation bar. You’ll see the following empty screen:

Adopted pets empty screen

Finally, press the Owners icon at the bottom navigation bar. This will show the screen for owners. Press the add button and you’ll see the following screen:

Add owner screen

The app is pretty much empty. It’s time to learn about Realm and use it to make this app work.

Introducing Realm

It’s time to begin your journey through the Realm. Although it might sound like some kind of magic, a Realm database is an object database management system. This type of database represents its entities as objects.

Importantly, Realm is ACID-compliant. This means a Realm database establishes:

  • Atomicity: by grouping all operations in a transaction. If any of the operations fails, then the database rolls back all the operations.
  • Consistency: by validating all changes with a schema.
  • Isolation: by allowing only one write operation at a time.
  • Durability: by saving immediately any change to disk.

To start using Realm, it’s important to learn some concepts to understand how it works.

Android teaching diagram

Understanding Realm

A realm is a set of related objects that have a predefined schema. You can have multiple realms in a single app. Each realm can have different permissions and can include different data types or objects.

A schema is a set of rules that define the types of data the database can store. You define this schema as a set of fields and their data types, in one or several objects called Realm objects.

A Realm object reads and writes data to and from the database. The database persists these objects. They always contain the latest values.

Each schema has a version. A change in the schema consists of adding or removing a field or adding a new realm object. You have to increment the schema version and create a migration to tell the database what changed in the schema.

Now that you know these basic concepts, it’s time to start using Realm. In the following section, you’ll add Realm to the sample project.

Initializing Realm

Open the project build.gradle file. In the dependencies section, add the following line after the navigation-safe-args-gradle-plugin dependency:

classpath "io.realm:realm-gradle-plugin:10.6.0"

Open the module build.gradle file to apply the plugin. Add the following line after the last apply plugin:

apply plugin: 'realm-android'
Note: Installing Realm this way will add every Realm dependency. However, it’s possible to add only the dependencies your app needs. You can refer to the official documentation to learn how to implement this.

Click sync now to synchronize the project. After the sync completes, open PetApplication.kt and add the following line in onCreate(), importing io.realm.Realm:

Realm.init(this)

This line initializes Realm and makes it available throughout the app. You can now get an instance of Realm and start adding objects and making queries.

Realm also needs a RealmConfiguration to setup the database. Open PetsModule.kt from the di package and add the following code, importing io.realm.RealmConfiguration:

// 1.
private val realmVersion = 1L

@Singleton
@Provides
fun providesRealmConfig(): RealmConfiguration =
  // 2.
  RealmConfiguration.Builder()
    .schemaVersion(realmVersion)
    .build()
  1. Declare a variable with the version for this schema.
  2. Use RealmConfiguration.Builder() to set the schema version and to build the RealmConfiguration.

Now, it’s time to build and run the app. It runs, but it still shows empty screens. The first step in adding functionality to the app is to create a schema.

Creating a Schema

PetRealm uses two entities: pets and owners. These entities create the schema of the database. The following diagram shows these two entities along with their fields.

PetRealm database entities

Both entities have an id to identify each element, thus making it the primary key. As you can see, there’s a mix of String, int and boolean data types, as well as NULL and NOT NULL fields. You need to define this information in each realm object.

Note: Realm supports different types of fields. For a complete list of these fields, visit the official documentation.

You’ll create the pet object first. In the realm package, create a new class and name it PetRealm.kt. Add the following code:

// 1.
open class PetRealm(
  @PrimaryKey // 2.
  var id: String = ObjectId().toHexString(), // 3.
  @Required // 4.
  var name: String = "",
  @Required
  var petType: String = "",
  var age: Int = 0,
  var isAdopted: Boolean = false,
  @DrawableRes
  var image: Int? = null // 5.
): RealmObject() // 6.

Import androidx.annotation.DrawableRes, io.realm.RealmObject, io.realm.annotations.PrimaryKey, io.realm.annotations.Required and org.bson.types.ObjectId.

There are several things going on here:

  1. You need to declare every entity class as open and every field as var.
  2. @PrimaryKey indicates the ID field is the primary key.
  3. Realm provides ObjectId() to create unique IDs for each object. You’ll use its hex representation.
  4. @Required indicates the field requires a value. Add this annotation to name and petType.
  5. For fields that allow null values, you can use nullable types and assign null as its default value.
  6. Each entity must be a RealmObject().

Create a class in the realm package and name it OwnerRealm.kt. Add the following code:

open class OwnerRealm(
  @PrimaryKey
  var id: String = ObjectId().toHexString(),
  @Required
  var name: String = "",
  @DrawableRes
  var image: Int? = null
) : RealmObject()

Import androidx.annotation.DrawableRes, io.realm.RealmObject, io.realm.annotations.PrimaryKey, io.realm.annotations.Required and org.bson.types.ObjectId.

With this code, you add the OwnerRealm entity to the Realm database.

Build and run the app. Behind the scenes, Realm adds PetRealm and OnwerRealm to the schema. However, you’ll still see an empty screen.

Still empty app

Now that you have created the schema, it’s time to insert some objects.