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
Deleting Objects
Open PetDatabaseOperations.kt and modify removePet()
as follows:
suspend fun removePet(petId: String) {
val realm = Realm.getInstance(config)
realm.executeTransactionAwait(Dispatchers.IO) { realmTransaction ->
// 1.
val petToRemove = realmTransaction
.where(PetRealm::class.java)
.equalTo("id", petId)
.findFirst()
// 2.
petToRemove?.deleteFromRealm()
}
}
To delete an object, you must:
- Query for the object you want to remove. This query should be in a transaction.
- Use
deleteFromRealm()
in that object to remove it from the database.
Removing objects that have a relationship requires an extra step. Open OwnerDatabaseOperations.kt and update removeOwner()
like this:
suspend fun removeOwner(ownerId: String) {
val realm = Realm.getInstance(config)
realm.executeTransactionAwait(Dispatchers.IO) { realmTransaction ->
// 1.
val ownerToRemove = realmTransaction
.where(OwnerRealm::class.java)
.equalTo("id", ownerId)
.findFirst()
// 2.
ownerToRemove?.pets?.deleteAllFromRealm()
// 3.
ownerToRemove?.deleteFromRealm()
}
}
You must:
- Query for the owner you want to remove.
- Use
deleteAllFromRealm()
to delete all the pets the owner has. - Finally, delete the owner object.
Build and run the app and delete some pets and owners. You can see that the pets from the owner get deleted if you remove the owner.
Now, PetRealm is complete. However, how can you debug the data in the Realm database?
Using Realm Studio
Realm Studio is a visual tool that helps you view, edit and create Realm databases. Head to Realm Studio website, and download and install version 11.1.0.
In Android Studio, go to View ▸ Tool Windows ▸ Device File Explorer. Select the emulator you’re using from the dropdown. Navigate to data ▸ data ▸ com.raywenderlich.android.petrealm ▸ files. Here, you can find the database with the name default.realm as shown in the next image:
Right-click the Realm filename and select Save As. Select a location on your computer and save the file. Now, open Realm Studio and press Open Realm file. Navigate to the saved file and select it. You’ll see the OwnerRealm schema first:
In it, you can see the current values for ID, name, image and pets. As you can see, the pets value is a list of pet IDs.
Select PetRealm in the left sidebar and you’ll see the following:
Click Create PetRealm at the top right and add the following pet:
Click Create and you’ll see the new pet added to the database.
Other operations you can do in Realm Studio are:
- Creating new classes
- Adding properties to existing classes
- Querying the classes
If you want to learn more about Realm Studio, visit the official documentation.
Now that you have learned about Realm, it’s time to talk about Room, one of the most popular persistence libraries in Android. What are the differences between Room and Realm?
Comparing Realm with Room
Jetpack provides Room, a data persistence library that uses SQLite behind the scenes.
You can store only primitive types and strings in Room. You can use type converters to convert an object to primitive types and store it in the database. For example, if you need to store a Date
, first you must convert it to Long
.
Room doesn’t allow entity objects to reference one another. This means when you work with relationships, you have to create intermediate classes to model these relationships between the entities. Here, you can find more information about relationships in Room.
On the other hand, Realm handles the object persistence itself. This means you can store primitive types, strings and any type of object and lists. Each object has to be an instance of RealmObject.
As you learned in the relationships section, you can use an inverse relationship to get the data of the related entity. You don’t have to do multiple queries to obtain the information you need.
Realm has other advanced functions like:
- Creating Realm Apps to sync data in real time between different platforms.
- Using App Services to authenticate and manage permissions.
- Working seamlessly with MongoDB.
Where to Go From Here
You can download the final project by using the Download Materials button at the top or bottom of the tutorial.
Realm database lets you store and access objects locally. You can insert data, query, filter and sort results, update and delete objects. It also provides a simple way to create relationships between entities.
If you want to learn more about Room, you can watch the Room Database: Getting Started video course. If you want to learn about DataStore, another way to store data in Android, visit DataStore Tutorial For Android: Getting Started. To learn more about other options to save data in Android, head to the Saving Data on Android video course.
I hope you enjoyed this tutorial on Realm. If you have any questions or comments, please join the forum discussion below.