HomeLearnHow-toIntroduction to the Realm SDK for Android

Introduction to the Realm SDK for Android

Published: May 14, 2021

  • Realm
  • Mobile
  • Kotlin
  • ...

By Mohit Sharma

Rate this article

This is a beginner article where we introduce you to the Realm Android SDK, dive through its features, and illustrate development of the process with a demo application to get you started quickly.

In this article, you will learn how to set up an Android application with the Realm Android SDK, write basic queries to manipulate data, and you'll receive an introduction to Realm Studio, a tool designed to view the local Realm database.

Pre-Requisites: You have created at least one app using Android Studio.

What is Realm?

Realm is an object database that is simple to embed in your mobile app. Realm is a developer-friendly alternative to mobile databases such as SQLite and CoreData.

Before we start, create an Android application. Feel free to skip the step if you already have one.

Step 0: Open Android Studio and then select Create New Project. For more information, you can visit the official Android website.

Now, let's get started on how to add the Realm SDK to your application.

Step 1: Add the gradle dependency to the project level build.gradle file:

1dependencies {
2 classpath "com.android.tools.build:gradle:$gradle_version"
3 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
4 classpath "io.realm:realm-gradle-plugin:10.4.0" // add this line
5}

Also, add mavenCentral as our dependency, which was previously jCenter for Realm 10.3.x and below.

1repositories {
2 google()
3 mavenCentral() // add this line
4}
1allprojects {
2 repositories {
3 google()
4 mavenCentral() // add this line
5 }
6}

Step 2: Add the Realm plugin to the app level build.gradle file:

1plugins {
2 id 'com.android.application'
3 id 'kotlin-android'
4 id 'kotlin-kapt' // add this line
5 id 'realm-android' // add this line
6}

Keep in mind that order matters. You should add the realm-android plugin after kotlin-kapt.

We have completed setting up Realm in the project. Sync Gradle so that we can move to the next step.

Step 3: Initialize and create our first database:

The Realm SDK needs to be initialized before use. This can be done anywhere (application class, activity, or fragment) but to keep it simple, we recommend doing it in the application class.

1// Ready our SDK
2Realm.init(this)
3// Creating our db with custom properties
4val config = RealmConfiguration.Builder()
5 .name("test.db")
6 .schemaVersion(1)
7 .build()
8Realm.setDefaultConfiguration(config)

Now that we have the Realm SDK added to our project, let's explore basic CRUD (Create, Read, Update, Delete) operations. To do this, we'll create a small application, building on MVVM design principles.

The application counts the number of times the app has been opened, which has been manipulated to give an illustration of CRUD operation.

  1. Create app view object when opened the first time — C R U D
  2. Read app viewed counts—C R U D
  3. Update app viewed counts—C R U D
  4. Delete app viewed counts— C R U D
Realm Android app

Once you have a good understanding of the basic operations, then it is fairly simple to apply this to complex data transformation as, in the end, they are nothing but collections of CRUD operations.

Before we get down to the actual task, it's nice to have background knowledge on how Realm works. Realm is built to help developers avoid common pitfalls, like heavy lifting on the main thread, and follow best practices, like reactive programming.

The default configuration of the Realm allows programmers to read data on any thread and write only on the background thread. This configuration can be overwritten with:

1Realm.init(this)
2val config = RealmConfiguration.Builder()
3 .name("test.db")
4 .allowQueriesOnUiThread(false)
5 .schemaVersion(1)
6 .deleteRealmIfMigrationNeeded()
7 .build()
8Realm.setDefaultConfiguration(config)

In this example, we keep allowQueriesOnUiThread(true) which is the default configuration.

Let's get started and create our object class VisitInfo which holds the visit count:

1open class VisitInfo : RealmObject() {
2
3 @PrimaryKey
4 var id = UUID.randomUUID().toString()
5
6 var visitCount: Int = 0
7
8}

In the above snippet, you will notice that we have extended the class with RealmObject, which allows us to directly save the object into the Realm.

We can insert it into the Realm like this:

1val db = Realm.getDefaultInstance()
2db.executeTransactionAsync {
3 val info = VisitInfo().apply {
4 visitCount = count
5 }
6 it.insert(info)
7}

To read the object, we write our query as:

1val db = Realm.getDefaultInstance()
2val visitInfo = db.where(VisitInfo::class.java).findFirst()

To update the object, we use:

1val db = Realm.getDefaultInstance()
2val visitInfo = db.where(VisitInfo::class.java).findFirst()
3
4db.beginTransaction()
5visitInfo.apply {
6 visitCount += count
7}
8
9db.commitTransaction()

And finally, to delete the object:

1val visitInfo = db.where(VisitInfo::class.java).findFirst()
2visitInfo?.deleteFromRealm()

So now, you will have figured out that it's very easy to perform any operation with Realm. You can also check out the Github repo for the complete application.

The next logical step is how to view data in the database. For that, let's introduce Realm Studio.

Realm Studio is a developer tool for desktop operating systems that allows you to manage Realm database instances.

Realm Studio is a very straightforward tool that helps you view your local Realm database file. You can install Realm Studio on any platform from https://docs.mongodb.com/realm/studio/.

Let's grab our database file from our emulator or real device.

Android studio

Detailed steps are as follows:

Step 1: Go to Android Studio, open "Device File Explorer" from the right-side panel, and then select your emulator.

Realm data in Android studio

Step 2: Get the Realm file for our app. For this, open the folder named data as highlighted above, and then go to the data folder again. Next, look for the folder with your package name. Inside the files folder, look for the file named after the database you set up through the Realm SDK. In my case, it is test.db.

Realm data in Android studio

Step 3: To export, right-click on the file and select "Save As," and then open the file in Realm Studio.

Realm studio

Notice the visit count in the VisitInfo class (AKA table) which is equivalent to the visit count of the application. That's all, folks. Hope it helps to solve the last piece of the puzzle.

If you're an iOS developer, please check out Accessing Realm Data on iOS Using Realm Studio.

If you have questions, please head to our developer community website where the MongoDB engineers and the MongoDB community will help you build your next big idea with MongoDB.

Rate this article

More from this series

Get Started With Realm and Android
  • Introduction to the Realm SDK for Android
  • Introduction to MongoDB Realm Sync for Android
MongoDB Icon
  • Developer Hub
  • Documentation
  • University
  • Community Forums

© MongoDB, Inc.