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.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Realm Database on Android: Getting Started
30 mins
- Getting Started
- Introducing Realm
- Understanding Realm
- Initializing Realm
- Creating a Schema
- Inserting Objects to the Realm
- Querying the Realm
- Filtering Results
- Sorting Results
- Making Calculations
- Adding Relationships
- Defining One-to-One Relationships
- Defining One-to-Many Relationships
- Using Inverse Relationships
- Migrating the Database
- Updating Objects
- Deleting Objects
- Using Realm Studio
- Comparing Realm with Room
- Where to Go From Here
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
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.
Press the button and you’ll see the screen to add pets, as shown below:
Dismiss the screen and press the Adopted pets option in the navigation bar. You’ll see the following 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:
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.
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'
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()
- Declare a variable with the version for this schema.
- Use
RealmConfiguration.Builder()
to set the schema version and to build theRealmConfiguration
.
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.
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.
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:
- You need to declare every entity class as
open
and every field asvar
. -
@PrimaryKey
indicates the ID field is the primary key. - Realm provides
ObjectId()
to create unique IDs for each object. You’ll use its hex representation. -
@Required
indicates the field requires a value. Add this annotation toname
andpetType
. - For fields that allow
null
values, you can use nullable types and assignnull
as its default value. - 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.
Now that you have created the schema, it’s time to insert some objects.