Getting Started with Realm Database – The Better Alternative to SQLite

What is Realm?

Realm is a database platform that offers some distinctive advantages over SQLite.

App developers have relied heavily on SQLite since the early days of Android, and no doubt it has been extremely useful. However, a distinct need for a less relational model was often felt, one where you didn’t have to add boilerplate code for converting values across the database or set up mappings between classes and tables, columns, fields and foreign keys among others.

Realm is a database that offers all of these advantages, as a database platform with an architecture more conducive to data structures used at application level. That is what makes Realm so popular among developers and an effective alternative to SQLite.

Realm is an embedded database system. It has similarities with SQLite but is actually completely distinct and has no relation to SQLite whatsoever. It is simpler to learn and use.

Realm’s core database engine is written from scratch in C++ rather than building an ORM on top of pre-existing, proven and full bodied database core engine like SQLite.

Realm is essentially a noSQL database which means that with Realm, you can store and retrieve data that is modeled in means other than tabular relations of relational databases. This makes for a much more familiar data structure that is easier to maintain. With less concatenating and less building queries or handling database connections manually, there is much less struggling and fewer typos.

Why should we use Realm?

  • Faster Queries – Realm provides results relatively faster than SQLite, and is much more performance minded.
  • Easy to use Realm is much simpler to use, thanks to it being an object database. By just creating a class that extends RealmObject class, you are all set.
  • Cross Platform utility – Good alternative to SQLite (Android) and CoreData(IOS).that can  be used across platforms like iOS, Xamarin and React Native too.
  • Easy creating and storing of data while on the move

Let’s get started

  • Open your Android Studio and create a new project from  File => New Project. Select Empty activity and proceed.
  • Add the classpath dependency in your project level build.gradle 
buildscript {
   dependencies {
      classpath "io.realm:realm-gradle-plugin:4.3.1"
   }
}
  • Add the realm-android plugin at the top of your application level build.gradle
apply plugin: 'realm-android'
  • The Realm App needs to be initialized just once, before it can be used. You can do this in the onCreate of an application subclass.
    public class MyApplication extends Application {
        @Override
        public void onCreate() {
           super.onCreate();
           Realm.init(this);
    }}
    

    Create your application subclass, and you must add it in app’s AndroidManifest.xml:

<application
   android:name=".MyApplication"
   ...
/>
  • You can save the RealmConfiguration as a default configuration. This will make it available to the rest of your code.
public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
//Realm initialization
    Realm.init(this);
    RealmConfiguration config = new RealmConfiguration.Builder().build();
    Realm.setDefaultConfiguration(config);
  }
}

Setting up the schema

Create a java class named Student.java. Realm data models are created by extending the RealmObject base class.

public class Student extends RealmObject {
    @PrimaryKey
    private int id ;

    private String name;
    private String father;
    private String std;

    //constructors, getters, setters
}

The @PrimaryKey annotation indicates that this field is set as a Primary key and must not be null.

The realm instance you created in the application subclass can be opened by calling Realm.getDefaultInstance(). The realm instance you open does however need to be closed in the end.

It is important that the Realm is closed on the background thread immediately after the execution is complete in a final block. Not doing this can cause strange errors. Also, when there are no more activities left, you can also close the Realm instance on your UI thread too.

Realm realm = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
   //...

   try{
       realm = Realm.getDefaultInstance();
       realm.executeTransaction(new Realm.Transaction() {

           @Override
           public void execute(Realm realm) {
               Number num = realm.where(Student.class).max("id");
               int nextId = (num == null) ? 1 : num.intValue() + 1;

               Student student = realm.createObject(Student.class, nextId);
               student.setName("Alicia");
               student.setFather("David");
               student.setStd("9C");

               realm.insertOrUpdate(student);
               }
          });
     } finally {
          if(realm != null) {
          realm.close();
     }
}

Getting data from Realm

The RealmResults<E> class holds all the matches of a RealmQuery for a given Realm. The Objects in this class aren’t really copied to the RealmResults lists from Realm. They are only referenced instead, helping you gain speed and memory.
RealmResults are live views, so if they are on an Looper thread, it will automatically update its query post a transaction. If they are on a non-looper thread, BaseRealm.waitForChange() will need to be called to update the results.

If you need to make any updates to RealmObjects from a RealmResults list, this needs to be done from within a transaction. All your modified objects can be persisted to the Realm file during the commit of the transaction.

Passing a RealmResults object between different threads isn’t a possibility.

@Override
public void execute(Realm realm) {

    final RealmResults<Student> students =realm.where(Student.class).equalTo(“name”, “Alicia”).findAll();
    for (Student s: students) {
        //...
    }
}

To get all the rows from the Student schema, we use .findAll() method, and to get just the first row, we call .findFirst()

@Override
public void execute(Realm realm) {
    final RealmResults<Student> students = realm.where(Student.class).equalTo(“name”, “Alicia”).findFirst();
    for (Student s: students) {
       //...
    }
}

Deleting data from Realm

Storing data in Realm is simple. Deleting data from Realm too is just as easy. You can delete object references, lists of data, particular objects, and even delete the entire data in a Realm database very easily.

@Override
public void execute(Realm realm) {
    RealmResults<Student> result = realm.where(Student.class).equalTo("id",5).findAll();
    result.deleteAllFromRealm();
}

Conclusion

So there you have it, a basic introduction to Realm, what it does, its advantages and how to get started with it. With that knowledge, you are now ready to start using Realm for your next app project. Do share your experiences with us in the comments section. Happy coding!

Checklist To Secure Your Mobile App From Every Possible Threat

Download Checklist
*We will send the checklist to your inbox and keep you updated with the latest trends and insights on app development to keep you on top of your game.
0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments