Streamlining Mobile App Databases with Realm.io

Share this article

This article was peer reviewed by Marc Towler. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

Despite most modern mobile apps requiring online access to send and receive data, at some point in app development you will need to store data locally on the device. For this you will need a local database.

Databases are generally slow at reading and writing data and Realm.io is a promising solution that can make development easy and offers a performance upgrade from SQLite on Android and Core Data on iOS.

Realm is a cross-platform mobile database released to the public in July of 2014 built from the ground up dedicated to run directly on phones, tablets and wearables. Realm is simple, fast and compatible across iOS & Android.

If you are not sure about its efficiency or why should you use it, check out its performance graphs.

Getting started with Realm on Android

You can download an example project based on this tutorial from GitHub.

Open build.gradle (app), add the dependencies needed and sync the project.

dependencies {
  …
   compile 'io.realm:realm-android:0.86.0'
}

Read the Java documentation for more detailed instructions.

Data models

Realm data models are based on Java Beans principles. A data model object looks something like this.

public class Contact extends RealmObject {

   private String name;
   private String email;
   private String address;
   private int age;

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public String getEmail() {
       return email;
   }

   public void setEmail(String email) {
       this.email = email;
   }

   public String getAddress() {
       return address;
   }

   public void setAddress(String address) {
       this.address = address;
   }

   public int getAge() {
       return age;
   }

   public void setAge(int age) {
       this.age = age;
   }
}

The java class presented above will represent a RealmObject of a person’s personal contact info and will store new contacts in memory and make queries to return those stored contacts.

Realm basic operations

As with any other database platform, the basic operations for a Realm database are known as CRUD operations (Create/Read/Update/Delete). This operations take place inside transaction blocks.

Realm supports both transactions on the main UI thread for small operations and transactions in a background thread to avoid blocking the UI thread for more complex operations.

To work with Realm, first get a Realm instance for the main UI thread.

Realm realm = Realm.getInstance(this);

Use this instance to work with a Realm database. Let’s try creating a Contact object and write it to Realm.

Realm handles write operations wrapped inside transaction blocks to ensure safe multithreading. A write operation looks something like this:

realm.beginTransaction();
Contact contact = realm.createObject(Contact.class);
contact.setName("Contact's Name");
contact.setEmail("Contact@hostname.com");
contact.setAddress("Contact's Address");
contact.setAge(20);
realm.commitTransaction();

Here Realm creates a new RealmObject based on the model class Contact.java. I added some values to the new object and the commitTransaction() method is called to end the transaction block. During the commit, all changes will be written to disk.

The same process can be accomplished by using the executeTransaction() method. This method automatically handles begin/commit transaction methods.

realm.executeTransaction(new Realm.Transaction() {
   @Override
   public void execute(Realm realm) {
       Contact contact = realm.createObject(Contact.class);
       contact.setName("Contact's Name");
       contact.setEmail("Contact@hostname.com");
       contact.setAddress("Contact's Address");
       contact.setAge(20);
   }
});

It’s good practice with Android to handle all writes on a background thread to avoid blocking the UI thread, so Realm supports asynchronous transactions. In the previous executeTransaction() method, just add a Realm.Transaction.Callback() parameter to make the process asynchronous.

realm.executeTransaction(new Realm.Transaction() {
   @Override
   public void execute(Realm realm) {
       Contact contact = realm.createObject(Contact.class);
       contact.setName("Contact's Name");
       contact.setEmail("Contact@hostname.com");
       contact.setAddress("Contact's Address");
       contact.setAge(20);
   }
}, new Realm.Transaction.Callback() {
   @Override
   public void onSuccess() {
       //Contact saved
   }

   @Override
   public void onError(Exception e) {
       //Transaction is rolled-back
   }
});

Queries

Working with queries is also simple with Realm. You don’t need to build complex queries and handle database exceptions like SQLException or CursorIndexOutOfBoundsException, the two most likely exceptions in SQLite.

//Query to retrieve all Contacts
RealmQuery<Contact> query = realm.where(Contact.class);
// Add query conditions: age over 18
query.greaterThan("age", 18);
// Execute the query:
RealmResults<Contact> result = query.findAll();
//Contacts stored in result

Or if you want it to run asynchronously:

// Execute the query asynchronously:
RealmResults<Contact> result = query.findAllAsync();

Deleting data from Realm is easy.

realm.beginTransaction();
result.remove(0);
realm.commitTransaction();

Remember, Realm operations are handled inside transaction blocks.

For those developers who are attached to traditional database principles, Realm offers a way to assign the RealmObject fields with annotations, special field properties to make them more ‘database field like’.

  • @Required – Enforces checks to disallow null values
  • @Ignore – Field should not be persisted to disk
  • @Index – Add a search index to the field
  • @PrimaryKey – Uniquely identifies each record in the database.

Relationships between RealmObjects are treated like relationships between tables in SQL databases.

If you are developing with a JSON data format, Realm has integrated methods to store and retrieve JSON data.

Something extra from Realm

It’s possible to integrate Realm with other commonly used libraries for Android. Make your app development easier and check out the libraries Realm integrates with.

Conclusion

To store data in an Android application you typically have to know SQL, understand the concept of Primary-keys, Foreign-keys and how to build a query and manage table relations.

Realm simplifies this and I feel will be a milestone in mobile storage. What do you think?

Valdio VeliuValdio Veliu
View Author

Valdio recently graduated in Computer Engineering. He is a mobile developer, who is passionate about mobile technologies and learning new things. He has worked with languages such as C, Java, php and is currently focused on Java, mobile and web development

chriswdatadatabasesmobile
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week