Realm Blog
Published in

Realm Blog

How to get started with Realm Sync in your Android Application

Hello and Welcome to my page, I am Henna =D.

This is the second article in the series “ Getting Started with MongoDB Realm in your Android Application” and I will talk about how to implement the Realm Sync feature in your Application.

Get your Coffee and your Laptop and Let’s roll on :D

EDIT02/02/22: This article has been revised based on the recent changes on Realm UI

Photo by Dayne Topkin on Unsplash

If you are new to this page, you will need to set up a MongoDB Cloud account and create a Realm App. You can follow part A of Article 1 of the series on how to do that

  1. Getting Started with MongoDB Realm

I have a bare-bones Note Keeper App without any data persistence added.

Please refer to the notelist.mp4 video on the Github link

This will also give you an overview of how to implement Realm Database in your already existing Android Application. If you have an app of your own, use that, or else you can clone the Note Keeper App below.

Note: Realm Sync Functionality is added in the same app but in the realm-sync branch.

Step 1: Creating MongoDB Realm Cloud Account to connect the App

If you have an account please log in and follow ahead.

Once you are in your account, Click on the Realm tab and create another Realm App either using a template or from scratch.

Enter details of the Realm Application that you are developing. You can link the app to the same cluster you created in Article 1 or you can create a new cluster. Click “Create a Realm Application after adding all details.

This will lead you to the dashboard of the application you have just created.

Make a note of “App ID”. You will need to add this to your Android App. Since we would be using Realm Sync in this app, Click on Sync from the left panel.

Please Note: Your App ID would be different than mine. Its a unique identifier for your Realm App.

Sync is not enabled by default. Once you click on “Start Syncing”, you would be prompted to a window as shown below

. If you already have data added to your Atlas database, you can click on “Generate a Schema” to generate schema for your mobile app or otherwise “Continue to Sync”. Click on “Continue to Sync” for this.

Next, you will be shown a window where you will configure Sync Details before enabling Sync.

Now, Sync has two types. Flexible Sync which is released in preview only recently, and Partition Sync which is based on partitions and also termed as Full Sync.

Once you select Sync type, Turn on Dev mode. Turning on dev mode allows us to make schema changes from the client (mobile). But this mode should be turned off once application goes in production.

Select your cluster that you created previously and define a meaningful database name where you want your notes to be saved.

In the next section, you define Partition Key and your Sync Permissions.

Choosing a partition key is an important concept. Its value defines the name of your realm that will store your collections. The partition key field name and type are final variables across your Realm Application. You can define different values of the field based on your use-case to make a private or public realm.

Permissions is another important concept and you can select a template that works for your case or create a JSON as desired. These permissions will determine who can read and write to your particular partition.

You can follow MongoDB documentation to read more on Partition Keys/Strategies and Development Mode and Sync Permissions.

Lets skip the Advance Configuration for purpose of brevity and will come back to this later. Click on Enable Sync.

Next, click on Review Draft and Deploy. You will need to do this everytime yo make any changes on the UI.

When you have deployed the changes, click on “Schema” from the left panel of your dashboard and you will see a blank page.

You will now make changes from your mobile application to populate the schema and collections on the Cloud.

Step 2: Adding Realm Dependencies

The very first step is to add Realm Database dependencies. We add dependencies in both project-level and app-level build.gradle file

  • Project-Level build.gradle file
classpath  "io.realm:realm-gradle-plugin:10.9.0”
  • App-Level build.gradle file
apply plugin: 'kotlin-kapt'
apply plugin: 'realm-android'
android {defaultConfig{
...
...
}
realm {
syncEnabled = true
}

...
}

Because the realm-android plugin depends upon the kotlin-kapt plugin for applications written in Kotlin, both plugins need to be added in the above order. Additionally, we need to enable Sync in the android block.

Please refer to MongoDB Realm documentation for the updated version of the Realm classpath

Once you add the dependencies, please perform the following 2 steps before you move on to the next section. You can check Article 1 on how these are implemented or you can copy the code from the Github repository from the realm_sync branch.

  1. Create an Application subclass and implement Realm App Configuration details.
  2. Add Login Activity and Google Authentication in your Realm or any provider of your preference and enable the same provider on the Cloud UI as explained in article 1.

After completing the above, you will modify model classes in the Android Application to persist data to the cloud.

Step 3: Updating Model Classes to Extend RealmObject

The Realm database can be used to persist data locally and also to the cloud if your application use-case requires. To persist changes to the cloud, we enabled Sync configuration on the MongoDB Realm Cloud account in step 2 above.

You linked your Cloud App to your Android app by using Realm App Id and configuring it in your Application subclass.

Now, the next step is to add data to the realm database. Realm follows Object Class Model to save your data.

The NoteKeeper App has only one model class and with 2 properties. The size and number of classes can vary depending on your use case.

//Beforeclass Note(
var noteName: String,
var date: Date = Date()
)

To persist data to the Realm database, you will make this model a sub-class of the RealmObject class.

This class should have all those fields that you would want to persist. The fields in the class will reflect in Atlas as a Document.

There are annotations that you can use for specific use-cases like the class will have a primary key marked with @Primary or some fields with @Ignored or @ Required It is important to include “_id” as a primary key as this is mandatory field for MongoDB Atlas. Also include “_partition” variable whose value determines which realm/partition the data will be part of.

Realm needs a public constructor with no arguments. When the default values are assigned, it becomes the properties of the class. So empty constructor is received by default. We define it as an open class because the realm extends the model classes internally for its operations.

In this case, the partition value is public which means, this will be a public realm, readable and writable by all. You can keep any string value you like, but for easy understanding, I am going with the value “public”.

The _id field is a mandatory field to be part of all model classes that you create for your use case. There are no local database rules around the _id field but it's required for syncing data to MongoDB. MongoDB on the cloud identifies documents via this field and it's an easy way to reference objects from another collection. By default_id is of type ObjectId in MongoDB but you are free to choose any type you want.

Now that you have created a Realm Object Model, you will now be able to write data to the Realm database and persist. When you login in your app again, you can retrieve data and display on the UI.

In the next step, you will modify TaskActivity to persist notes to the realm database so that they are not lost when you re-open the app.

Step 4: Editing TaskActivity to persist Notes to Realm Database

Now, in your TaskActivity, you will define two variables as shown below:

private lateinit var realm: Realm
private var user: User? = null

Next, you will configure Realm instance in the onStart() method of your TaskActivity.

Please Note: There is a difference in RealmConfiguration and SyncConfiguration. RealmConfiguration is used to open local Realms when data is stored only locally. SyncConfiguration API is used when you are opening a synced realm.

The code explanation is as follows:

  1. you get the reference of the logged-in user.
  2. you configure Realm instance to use the current user and the public partition. As this is a public realm, and you created a partition key on the cloud of type String, so you pass in the string value. You wait for the initial data if there is any on the server to be downloaded
  3. Here, you get a Realm Instance Asynchronously, so that downloading happens in the background thread and does not block the UI and on successful download, you assign the value to the member variable.

The Realm class is the storage and transactional manager of your object persistent store. It is in charge of creating instances of your RealmObjects.

Now that you have created the configuration and the realm instance, the next step is to save the notes to the realm database as and when they are created.

This whole logic is done on clicking the floating action button. Now, you will edit the logic to save data to your Realm db.

Here, saving the data to the realm database is accomplished in two steps

  1. Insert note to the realm database instead of passing to the adapter
  2. Retrieve data from Realm and pass it to RealmRecyclerViewAdapter to display it on the UI.

Realm provides RealmRecyclerViewAdapter that you can extend to customize for your application and here we will modify NoteAdapter class to use the same to display the list of notes on the screen.

Explanation of RealmRecyclerViewAdapter is out of scope of the article, so you can copy below code and use that. Add the following dependency to your app level build.gradle file.

implementation "io.realm:android-adapters:4.0.0"

Now to accomplish step 1, you will insert the note in realm inside an async transaction. The click listener after changes will look like below:

Objects within a Realm can be queried and read at any time. The CRUD operations must be done while inside a transaction.

The transactions can be synchronous or asynchronous. Synchronous transactions are done on a UI thread and can lead to ANR errors, that's why we are using the async method to do our insert operation.

You can refer to Realm Java API at MongoDB official documentation for methods that suit your use case.

Now, back in TaskActivity, you will set up the Recycler view to get data from the realm database. Add a call to the following method in onStart() the method of the Activity inside the onSuccess() call of getting the Realm Instance.

  1. This is how you query objects inside Realm. This is similar to the SELECT clause in SQL databases. Realm follows a syntax as shown. It will display the list of notes sorted by date.

It is important to close realm instances when we are done with them. Here, you will override theonDestroy() method to close the Realm Instance.

Now, the next step is to run the app and add some notes, then login to your Cloud Account and see your Atlas Collections, your data is on the cloud. Magic ;)

To check your data on Atlas, go to the Atlas tab and click on ”Browse Collections”, and you will see the list of notes added via the device.

As this is the first time, you are syncing data, it may take 2–4 minutes for data to appear on the Cloud. There will be instantaneous sync after that.

Challenge: Insert a note from the cloud (1), Please ensure you follow the type as you added in your schema on the device and format as other documents and see it syncing back to your device.

In your Realm tab, when you click on the schema from the left panel and you will see the model is populated with what you created in your application. =D

Yay!!! We did it. We learned how to implement MongoDB Realm Sync in the Android application.

Challenge: Now, for the last step, add a logout button to your app, log in with a different user and you will see the notes available to this user as well. Hence, you created a shared realm, readable and writable by all .. YAY!

Photo by Priscilla Du Preez on Unsplash

I hope you enjoyed reading the article and it helped you understand the basics of MongoDB Realm Sync. I would appreciate it if you would have any feedback for me ❤ ❤

You can post questions on MongoDB Community Forums or if you are struggling with any topic, please feel free to reach out.

The next article talks about how to create a mobile app if you already have data in MongoDB Atlas

Happy Coding!!

--

--

--

Build better apps, faster. Realm open-source database helps developers build offline-first apps in a fraction of the time. SDKs for Swift, Objective-C, Java, Kotlin, C#, and JavaScript. Visit us at https://realm.io

Recommended from Medium

Public testing of Android app starts now!

Draw a path with animation

Build BMI Calculator App in Flutter using Dart in Android Studio🚀

Vertical Mode of Chip Navigation Bar Android(Kotlin).

My Findings on Gradle Android Test Plugin

Using Android Content Providers for Automatically Initialization

Autofill Services Android Part-2

Lessons from my first multiplatform Kotlin project

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Henna Singh

Henna Singh

Technical Speaker and an aspiring writer with avid addiction to gadgets, meet-up groups, Kotlin and paper crafts.

More from Medium

A Mix of BookLog and Flashcards

Push project to github in android studio

Developing Using HMS Kit on Trevor — To Do List App

Cross-Platform App Development Vs. Native App Development

native vs cross-platform