Exploring the vastness of the Realm, a cross-platform mobile database

Marcos Placona
Aug 17, 2016 · 7 min read
Image for post
Image for post

If you’re an Android developer chances are you’ve used SQLite for internal storage in your mobile apps and know how painful it is to set it up.

Realm is a cross-platform mobile database engine that aims to provide developers with a mobile-first engine, super powered with fluent interfaces and field annotations. Here’s an example of how easy it is to use:

Let’s look at how to build an application that stores your notes in a Realm database.

What You’ll Need

There are no other requirements to complete this tutorial since all you need is Android Studio, though you could probably use any other IDE’s you prefer.

If you don’t feel like going through the entire process of setting up the app, feel free to just clone my Github repository here.

Setting up

Choose API 16 as the Minimum SDK and Basic Activity as your starting point for this application. This will come with a pre-baked Floating Action Button which we will modify and use later on.

Click Finish on the next screen and you’ll be ready to start building the application.

Image for post
Image for post

Getting our dependencies

Image for post
Image for post

Now open your application-level build.gradle and apply the Realm plugin and install some libraries:

Image for post
Image for post

We’ve added a library called RealmRecyclerView which is a RecyclerView wrapper for working with Realm as a datastore. It gives us some nice functionalities like pull-to-refresh and swipe-to-delete out of the box.

One thing to note here is that the major version of the RecyclerView needs to match the version on compileSdkVersion.

The IDE will ask you to sync. Let it do its thing as we’re just about to work on the app’s interface.

User Interface

We’re now going to add a TextField and a RecyclerView to our layout so we can add and display our notes. Open app/res/layout/content_main.xml, delete the existing code for the TextView and replace with:

Each one of the items in a RecyclerView is displayed individually and the rows inflate their own layout. Let’s create this layout by creating a new Resource File in app/res/layout called note_item.xml and replace its contents with:

I think we should give it a spin now by pressing the Run button to make sure everything is working well. If you see something like this you’re all good.

Image for post
Image for post

Notice that if you try to create a note right now nothing will happen as we’ve still not hooked this application up with our database. We will move on to that right now.

Entering the Realm

Go to app/java/{your_chosen_domain}.realmnotes and create a new Java class called Note.java. This class will contain the definition of our database along with any defaults we may wish to create such as IDs and dates:

As you can see this is just a POJO that implements RealmModel.

This is important because it tells Realm this is not only an Object, but aRealmObject. You can find more about Realm entity relationships here. It also has a class annotation that lets Realm know this is a database object.

Now that we’ve defined what our database is going to look like, let’s head back toapp/java/{your_chosen_domain}.realmnotes and open MainActivity.

Start by adding member variables to all the widgets we’re going to use to the top of the class and then on the onCreate method add the references to those:

We’ve also added the mRealmConfig and mRealm definitions, which initialise Realm. Running the application now and clicking the plus button will result in aSnackBar message being displayed on the screen and nothing more.

Image for post
Image for post

The SnackBar says “Replace with your own action” which is convenient as this is exactly what we’re going to do now. Change the floating action button’s onClickListener to call the insertNote method :

Now create that method below the onCreate method and define it so it takes a String and uses Realm to add to the database:

The above is all it takes to add a new item to the database. We initialise our object and the copy it straight to Realm. Give it another spin and you should see that when you add a new note, the SnackBar shows a different message.

You will also notice that nothing gets displayed as we still aren’t loading the messages from our database.

Exploring the Realm

Image for post
Image for post

We should now have a database that is eager to display some results so let’s satisfy that by fetching those results from the database and displaying them on our RecyclerView.

Start off by creating an Adapter that will serve as a bridge between our dataset and our widget. Create a new inner class in MainActivity calledNoteRecyclerViewAdapter that extends RealmBasedRecyclerViewAdapter.

If we were using a normal RecyclerView we would just extendRecyclerViewAdapter. Since we’re using a modified version of it we need to extend a different class:

This class looks a lot more complicated than it actually is but if you’ve used Adapters in Android before you’re probably feeling “at home”.

Our class takes a Context and a results object as arguments for its constructor. It then goes on to define a ViewHolder which just like the name suggests holds information about the view we’re trying to display.

The ViewHolder is based on the layout resource file we created earlier and callednote_item.xml.

We then override two of its methods. One for when the view holder is created so we inflate our layout inside it and another one for when the view holder is already loaded and we know it’s safe for us to add data to it.

Now we just need to load the data from the database and pass it to our adapter. Add a call to a method named loadNotes() to the bottom of the onCreate method in the MainActivityClass.

Create a method below onCreate with that same name. It will be responsible for loading our notes and adding them into our view adapter:

We’re querying the database by asking it to return any entities that are stored in the database for our Notes model. We’re using the findAllSorted method without passing any filters. You can read more about querying a Realm database here.

Give the app another go and what you should see now is that the notes you created earlier are displayed in the list. Also try adding a new note and see how the RecyclerView gets refreshed automatically.

Image for post
Image for post


The last trick I want to show you is one that is useful when you have lots of notes and it becomes hard to find things. With the wrapper we’re using we have the option to add headers to the adapter so we can display something more organised like this:

Image for post
Image for post

To get these headers working you need to change the classNoteRecyclerViewAdapter to be constructed with the following:

We’ve added two extra arguments to the end of the call to super. One specifies that we want to show headers and the second says that we want it to be ordered by the text property on our model.

You own the Realm

The ease of use and ability to get a database up and running in minutes surely makes me want to build a lot more with it. I can’t wait for you to tell me what you’ve built. Hit me up on Twitter @marcos_placona or by email on marcos@twilio.com to tell me about it.

Disclaimer: This is a cross post from my original post on the Twilio Blog

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

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