Realm vs SQLite: What Database is More Appropriate for Android Apps

FREE Online Courses: Your Passport to Excellence - Start Now

In the process of Android app development, programmers should choose a database to store the data this app uses. An inappropriate database may lead to data loss or some other problems with app performance, that is why developers should make a proper decision. That’s why today we are discussing Realm vs SQLite, for selecting the most appropriate database. 

There are many databases, but we would like to compare two the most popular databases – SQLite and Realm – for Android apps and this guide will help you make your choice to use the database appropriate for your project. SQLite vs realm – which one is stronger?

Realm vs SQLite

Realm vs SQLite

Learn core aspects of Android Operating System

What is SQLite and Realm Databases?

First, let’s understand these two databases, what they are and how they work.

SQLite

This database was created in far 2000. It is free and open source. The particularity of SQLite is that It doesn’t use server-client architecture and it allows developers to store the app on a mobile device. That is why so many programmers use it when they need all information to be stored on a device without the necessity to use the server.

The database is created using C language and more than 30 programming languages can be used to work with this DB. For today, tens of thousands of apps design using an SQLite database.

Realm

Realm is a NoSQL database that makes it possible for programmers to declare relationships between objects, as developers can do it in object graph of any programming language. Realm today is used for Android app development rather often.

The realm has its own core written in C++. This database is cross-platform so we can use it for both for iOS and Android. Realm allows objects to update synchronously. So object respond to any changes instantly and they stores easily. The realm is also open source since 2016 and it is free for developers.  

Explore Top Features of Android

Advantages and Drawbacks of SQLite and Realm

Now, let’s define strong and weak sides of two databases to let you understand all particularities of SQLite and Realm.

SQLite advantages

  • Single file. The whole database is stored only in one file, so its migration is simplified in many times.
  • Standard. SQLite uses SQL, so despite the fact that some SQL features are not implemented by SQLite (like RIGHT OUTER JOIN, FOR EACH STATEMENT etc.), many SQL features remain the same in SQLite.
  • SQL language extensions. There are some enhancements to the SQL language that other database engines lack. New APIs can be defined by SQLite and developer can add new SQL functions.
  • Good for development and even testing. Developers often need scalable solution during the development process. SQLite has rather a large functionality so developers can get features they need, and it even makes it possible to test an app.

SQLite drawbacks

Actually, SQLite will be a perfect choice for small and not too complicated projects. However, when developers create large Android apps with complex structure, they will face the following challenges:

i. Security

As SQLite has a specific structure and other particularities, developers should consider some issues related to security before they will work with SQLite when creating Android apps. First, the SQLite database is in one file, and this file gets place in any directory. Thus, an advantage can turn into a drawback. Yes, it is very convenient, but in the result, there is a high risk that some malicious process can open this DB and make certain changes. So the level of security should be high, and developers should set permissions properly and don’t let files deal with web root.

One more problem with security concerns journaling. If developers want to have a rollback option, there is a temporary journal file by the database. When the transaction performs, all files gets delete. However, in some files remain unchanged. And it may lead to data corruption in SQLite databases due to its specific particularities. Turning off the journaling will not solve the problem. In this case, if there is an app crash, the database gets damages. To avoid such problems, we can encrypt data before its putting into SQLite.

Understand the 5 Components of Android Architecture

ii. Scalability and support

Of course, the database grows exponentially when new data adds constantly. And developers need to write more complicated queries, but this is a big challenge for young programmers who are not skilled yet at structured query language. Data migration has the same problem.

iii. Complexity

When are senior developers easily deal with SQLite, it doesn’t mean that newcomers will do it also as good as more experienced colleagues. The complex massive structure of SQLite is a big challenge for young specialists.

Realm Advantages

  • High speed. Realm is very fast during Android app development.
  • Documentation. All documents concerning Realm are written properly, and specialists can find an answer on the official website if they need.
  • Accessibility. Developers can copy objects in Realm that remain available outside of Realm.
  • More features. Realm offers new useful features like JSON support, encryption, fluent API – it is not the full list. Also, Realm offers notifications of data change.

Realm Drawbacks

  • APK size becomes bigger and more RAM utilize.
  • No Auto-increment. You cannot auto-increment values in Realm.
  • Restrictions on Model classes. Methods like hashcode and equals cannot be nullified in classes of Realm Model.

Check out the Steps to Install Android Studio

Realm vs SQLite in Coding

It is time to compare realm vs SQL through their codes. We will show a few code samples written using SQLite and Realm. As we can see, Realm allows you to write less code. But first things first.

private static final String SQL_CREATE_FAVOURITE =
          "CREATE TABLE " + FavouritesDBContract.FavouritesEntry.TABLE_NAME + " (" +
                   FavouritesDBContract.FavouritesEntry._ID + INTEGER_TYPE + " PRIMARY KEY AUTOINCREMENT," +
                   FavouritesDBContract.FavouritesEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
                   FavouritesDBContract.FavouritesEntry.COLUMN_NAME_IMAGE_URL + TEXT_TYPE +
                   " )";
public void onCreate(SQLiteDatabase db) {
       db.execSQL(SQL_CREATE_FAVOURITE);
   }

Source – cleveroad

In Realm it will be enough to inherit RealmObject only

public class Favourites extends RealmObject{
  String title;
   String imageLink;
   @Nullable
   ImageResponse image;
public Favourites(String title, String imageLink, @Nullable ImageResponse image) {
       this.title = title;
       this.imageLink = imageLink;
       this.image = image;
   }
}

One more example. You want to create a query to get a list of results. In SQLite you will need to write such code:

@Override
public void getFavorites(int page, GetFavouritesCallBack callback) 
 List<Favourites> favourites = new ArrayList<>();
  try {
   Cursor cursor = mDb.query(
    FavouritesDBContract.FavouritesEntry.TABLE_NAME,  null, null, null, null, null, null);
     if (cursor != null && cursor.getCount() > 0) {
      while (cursor.moveToNext()) {
        String title = cursor
                           .getString(cursor.getColumnIndexOrThrow(FavouritesDBContract.FavouritesEntry.COLUMN_NAME_TITLE));
                   String imagePath =
                           cursor.getString(cursor.getColumnIndexOrThrow(FavouritesDBContract.FavouritesEntry.COLUMN_NAME_IMAGE_URL));
                   Favourites favourite = new Favourites(title, imagePath, null);

                   favourites.add(favourite);
               }
           }
       } catch (IllegalStateException e) {
           callback.onDataNotAvailable();
       }
   }

But Realm code will be less complex for the same operation:

public List<Favourites> getFavorites() {
      Realm realm = getRealm();
       List<Favourites> favourites = realm.where(Favourites.class).findAll();
       favourites = realm.copyFromRealm(favourites);
       realm.close();
       return favourites;
   }

Code to perform data migration is also very complicated in SQLite and this process is unavoidable, developers will need to perform it in any case. So, what a code should be like in SQLite during Android app development:

public class FavouritesMigration implements RealmMigration {
  @Override
   public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
       RealmSchema schema = realm.getSchema();
       if (oldVersion == 1) {
           schema.get("Favourites")
                   .removeField("image");
           oldVersion++;
       }
   }
}

Also, in config this code gets add:

private static final RealmConfiguration mConfig = new RealmConfiguration.Builder()
           .schemaVersion(FAVOURITES_SCHEMA_VERSION)
           .migration(new FavouritesMigration())
           .build();

So, this was all in Realm vs SQLite. Hope you liked our explanation.

Must Learn: Major Android Application Components

Summary – Realm vs SQLite

Well, more code doesn’t mean that SQLite is a bad database. As we listed above, it has some obvious benefits, so both Realm and SQLite are for different projects and various purposes. Each of them has its particular strength. It is worth noting that it is up to developers to decide which database will be a perfect option for Android app development.

Still, if you have any query regarding Realm vs SQLite, ask freely through comments.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *