A small library to help with Realm.IO integration in Android apps

Overview

Circle CI Release GitHub license

Android Realm Asset Helper

A small library of methods to help with Realm.IO integration in Android apps

Copies a realm database from a the assets folder. Efficienty handles versioning of read-only realm databases.

About

Motivated by direct support for read-only databases in iOS app bundles and modelled on ideas in Android SQLite Assset Helper, the goal of this library is to help with some common tasks found with using Realm.io in Android. It is actively maintained and used by Egghead Games for their Andriod & iOS brain puzzle apps.

Features

  • copy the realm db from the app bundle and return filename ready to be opened
  • easy, efficient updating of read-only databases

Simplest Example

In this simplest scenario, the library handles locating and copying the realm file from your apk into the Android file system so it is ready to use.

Say your app has a single Realm database that ships with some sample data. You need to copy that database on first install so it is ready to use in your app. Store your file called, say, appdata.realm in your assets/data folder and include code like this:

import com.eggheadgames.realmassethelper;

Realm realm;

RealmAssetHelper.getInstance(context).loadDatabaseToStorage("data", "appdata", new IRealmAssetHelperStorageListener() {
    @Override
    public void onLoadedToStorage(String realmDbName, RealmAssetHelperStatus status) {
                realmConfig = new RealmConfiguration.Builder(context)
                        .name(realmDbName)
                        .build();
                realm = Realm.getInstance(realmConfig);
            }
    }
});

This will:

  • find appdata.realm in assets/data folder
  • see if there is an existing appdata.realm already installed
  • copy the appdata.realm from assets/data only if no pre-existing file is found
  • return the realm file name and status

Read-only Data Example

Another scenario is where you include a large amount of data to use read-only in your application, such as product catalogue information or game level data.

Say you have the 3rd version of your company's products.realm database to ship with your latest apk. Store it in assets/data with the name products_3.realm, then load it with:

RealmAssetHelper.getInstance(context).loadDatabaseToStorage("data", "products", new IRealmAssetHelperStorageListener() {
    @Override
    public void onLoadedToStorage(String realmDbName, RealmAssetHelperStatus status) {
                realmConfig = new RealmConfiguration.Builder(context)
                        .name(realmDbName)
                        .build();
                realm = Realm.getInstance(realmConfig);
            }
    }
});

This will:

  • find the products_3.realm in assets/data folder
  • see if there is an existing products.realm installed and check a sharedPreference value to see what version it is
  • copy the realm data if it is newer (removing the _3)
  • return the realm file name and status

Installation Instructions

Add the JitPack.io repository to your root build.gradle:

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}

Add a dependency to your application related build.gradle

dependencies {
    compile 'com.github.eggheadgames:android-realm-asset-helper:2.1.0'
}

Explanation

It can be convenient to have a read-only database as part of an apk. This might have game level information, for example, or other data like zip codes or product information. If the app treats it as "read-only" (perhaps also using a separate realm database for storing other state data), then data updates are as simple as updating the "master" realm file in the apk and then copying it over on first run after the user updates.

iOS note: This is conceptually simpler in iOS, because realm can access read-only data directly from the application bundle (= apk). This library was originally created so that our iOS and Android apps could share the same read-only realm database.

This helper library adds support for this "read-only data included in apk" scenario.

For efficiency, the copy should only be made when the database has changed. This is handled as follows:

  • if no copy of the database exists, it is copied
  • if a copy exists, then a sharedPreference value is checked to see what database version it is (defaults to 0 if not found)
  • the APK assets folder is searched for the database name with a postfix _NN in the name (e.g. products_12). If the NN value is higher than the current version, then the new database is copied (with the _NN removed) and the sharedPreference value is updated
  • if no database is found in assets, this causes an immediate error (as this is usually an oversight and should be resolved ASAP)

Thus, the workflow for an apk with read-only data becomes:

  • store the database, e.g. products in assets with the name products_0
  • when products is updated, rename the fie from products_0 to products_1

The helper will see the change and copy the database as needed.

Caveats

There is no consideration given (so far) to database migration requirements or any sort of "update my user's existing realm database from this new realm database". That is clearly a useful enhancement to think about for the future but was beyond the scope of the initial release.

Pull Requests, Issues, Feedback

We welcome pull requests. If you have questions or bugs, please open an issue and we'll respond promptly.

You might also like...
A key-value database for Android
A key-value database for Android

SnappyDB SnappyDB is a key-value database for Android it's an alternative for SQLite if you want to use a NoSQL approach. It allows you to store and g

Insanely easy way to work with Android Database.

Sugar ORM Insanely easy way to work with Android databases. Official documentation can be found here - Check some examples below. The example applicat

Android Database Performance Benchmarks

ℹ Check out our new performance test app that includes ObjectBox. Android Database Performance Benchmark This project evaluates Android databases and

Core Data for Android

NexusData Core Data for Android NexusData is an object graph and persistence framework for Android. It allows for organizing and managing relational d

🧬 Android DataBinding kit for notifying data changes from Model layers to UI layers on MVVM architecture.
🧬 Android DataBinding kit for notifying data changes from Model layers to UI layers on MVVM architecture.

🧬 Android DataBinding kit for notifying data changes from Model layers to UI layers on MVVM architecture.

Kodein-DB is a Kotlin/Multiplatform embedded NoSQL database that works on JVM, Android, Kotlin/Native and iOS.
Kodein-DB is a Kotlin/Multiplatform embedded NoSQL database that works on JVM, Android, Kotlin/Native and iOS.

Kodein-DB is a Kotlin/Multiplatform embedded NoSQL database that works on JVM, Android, Kotlin/Native and iOS. It is suited for client or mobile applications.

 Android with Real-time Database
Android with Real-time Database

Android with Real-time Database It was too much effort to build my own real-time database, but the result really satisfying, so it was worth it. Note

Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock
Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock

This kata is a Kotlin multiplatform version of the kata KataTODOApiClientKotlin of Karumi. We are here to practice integration testing using HTTP stub

FilePicker is a small and fast file selector library that is constantly evolving with the goal of rapid integration, high customization, and configurability~
FilePicker is a small and fast file selector library that is constantly evolving with the goal of rapid integration, high customization, and configurability~

Android File Picker 🛩️ 中文简体 Well, it doesn't have a name like Rocky, Cosmos or Fish. Android File Picker, like its name, is a local file selector fra

Android News Reader app. Kotlin Coroutines, Retrofit and Realm
Android News Reader app. Kotlin Coroutines, Retrofit and Realm

News Reader Android News Reader app Code that follows Packt Publishing Kotlin in Practice Video Course Example of Kotlin Coroutine usage, with Realm a

Android News Reader app. Kotlin Coroutines, Retrofit and Realm
Android News Reader app. Kotlin Coroutines, Retrofit and Realm

News Reader Android News Reader app Code that follows Packt Publishing Kotlin in Practice Video Course Example of Kotlin Coroutine usage, with Realm a

Android News Reader app. Kotlin Coroutines, Retrofit and Realm
Android News Reader app. Kotlin Coroutines, Retrofit and Realm

News Reader Android News Reader app Code that follows Packt Publishing Kotlin in Practice Video Course Example of Kotlin Coroutine usage, with Realm a

A simple ToDo app to demonstrate the use of Realm Database in android to perform some basic CRUD operations like Create, Update and Delete.
A simple ToDo app to demonstrate the use of Realm Database in android to perform some basic CRUD operations like Create, Update and Delete.

Creating a Realm Model Class @RealmClass open class Note() : RealmModel { @PrimaryKey var id: String = "" @Required var title: String

Realm is a mobile database: a replacement for SQLite & ORMs

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the Java version of Realm

Realm is a mobile database: a replacement for SQLite & ORMs

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the Java version of Realm

Samples demonstrating the usage of Realm-Kotlin SDK
Samples demonstrating the usage of Realm-Kotlin SDK

Realm-Kotlin Samples This repository contains a set of projects to help you learn about using Realm-Kotlin SDK Each sample demonstrates different use

Collection of Kotlin APIs/tools to make using Realm Mobile database easier

Compass Kotlin API and tools to make working with Realm easier Components Compass is designed to make working with Realm easier through collection of

KmMScientists is a Kotlin multiplatform app with swift ui, jetpack compose, koin and realm
KmMScientists is a Kotlin multiplatform app with swift ui, jetpack compose, koin and realm

KmMScientists KmMScientists is a Kotlin multiplatform app built with swift ui, jetpack compose, koin and realm. Whats Shared? Local Data Persistence w

Small library that allows the application to display a small troubleshooting guide in case of repeated app startup crashes.
Small library that allows the application to display a small troubleshooting guide in case of repeated app startup crashes.

AppSalvager What is it? AppSalvager allows you to combat the issue of repeating crashes on app startup. Failed data migration, SDKs not handling their

Comments
  • OutOfMemoryError

    OutOfMemoryError

    Some device crashed when loading the database during application onCreate. Any idea?

    Fatal Exception: java.lang.OutOfMemoryError at com.eggheadgames.realmassethelper.OsUtil.loadDatabaseToLocalStorage(Unknown Source) at com.eggheadgames.realmassethelper.RealmAssetHelper.getInstance(Unknown Source) at com.myapp.MyAppApplication.onCreate(Unknown Source) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:999) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4218) at android.app.ActivityThread.access$1300(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1275) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4812) at java.lang.reflect.Method.invokeNative(Method.java) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) at dalvik.system.NativeStart.main(NativeStart.java)

    opened by shiami 5
  • Cannot resolve symbol `realmConfig`

    Cannot resolve symbol `realmConfig`

    Doesn't compile, error: Cannot resolve symbol realmConfig Realm v 2.3.2

    Looks like the code should look like that:

    Realm.init(this);
    
            RealmAssetHelper.getInstance(this).loadDatabaseToStorage("data", "defaultpacked", new IRealmAssetHelperStorageListener() {
                @Override
                public void onLoadedToStorage(String realmDbName, RealmAssetHelperStatus status) {
                    RealmConfiguration realmConfig = new RealmConfiguration.Builder()
                            .name(realmDbName)
                            .build();
                    Realm realm = Realm.getInstance(realmConfig);
                }
            });
    
    opened by Drag11 2
  • Unsupported Realm file format version (11)

    Unsupported Realm file format version (11)

    When trying to read a realm file in a blank android project following the description in the readme.md I get the following error

    Caused by: io.realm.exceptions.RealmFileException: Unable to open a realm at path '/data/data/myapp/files/default.realm': Unsupported Realm file format version (11)

    I have the following questions: I assume the (11) represents the version of the database file that I supply, correct? Which database versions is the android-realm-asset-helper compatible with. Is my file too old or too new?

    I'll be glad for any help :)

    opened by lor-enz 1
  • I try to use it but give me  java.lang.RuntimeException: An asset for requested database doesn't exist

    I try to use it but give me java.lang.RuntimeException: An asset for requested database doesn't exist

    I put my test.realm in assets folder /data/test.realm

         RealmAssetHelper.getInstance(this).loadDatabaseToStorage("data", "test.realm", new   
          IRealmAssetHelperStorageListener() {
             @Override
             public void onLoadedToStorage(String realmDbName, RealmAssetHelperStatus status) {
                  RealmConfiguration  realmConfiguration = new RealmConfiguration.Builder(MainActivity.this)
                          .name(realmDbName)
                          .build();
                  realm = Realm.getInstance(realmConfiguration);
               }
    
          });
    
    opened by droidahmed 1
Releases(2.1.0)
  • 2.1.0(May 16, 2020)

    • Fix OutOfMemory problem on older / lower specification devices
    • Update Android TargetSDK from 23 to 29
    • Update to CircleCI 2.0
    • Update Android Gradle Tools from 1.5.0 to 3.5.3
    • Add SpotBugs tests and clean up minor items it found
    Source code(tar.gz)
    Source code(zip)
Owner
Quality Mobile Puzzle Apps
Quality Mobile Puzzle Apps
A helper library to help using Room with existing pre-populated database [].

Room now supports using a pre-packaged database out of the box, since version 2.2.0 https://developer.android.com/jetpack/androidx/releases/room#2.2.0

Ibrahim Eid 136 Nov 29, 2022
Test any type of cloud database on Android apps. No need of a dedicated backend.

Test any type of cloud database on Android apps. No need of a dedicated backend.

Arjun 9 May 9, 2022
Android library for viewing and sharing in app databases.

DbInspector DbInspector provides a simple way to view the contents of the in-app database for debugging purposes. There is no need to pull the databas

Infinum 925 Dec 17, 2022
an android library for debugging what we care about directly in app.

EN | 中文 Pandora is a tool box that allows you to inspect and modify what includes networks, databases, UIs, etc. directly in your application. It is s

linjiang 1.5k Dec 30, 2022
Pref-DB - Android SharedPreferences alternative library

Pref-DB Android SharedPreferences alternative library.

M.Fakhri 5 Sep 14, 2022
A library for reading Shared Preferences and Database values within the application.

AppDataReader A library for reading and writing Shared Preferences and Database values of the application within the device. Advantages of using this

Anshul Jain 124 Nov 25, 2022
A quick and easy database manager plugin library for your DBFlow databases.

DBFlowManager A quick and easy database manager and viewer plugin library for your DBFlow databases to view, insert, delete, update the tables directl

Wajahat Karim 26 Oct 21, 2022
An Android helper class to manage database creation and version management using an application's raw asset files

THIS PROJECT IS NO LONGER MAINTAINED Android SQLiteAssetHelper An Android helper class to manage database creation and version management using an app

Jeff Gilfelt 2.2k Jan 7, 2023
A wrapper around Android's SQLiteDatabase with restoring capability

Restorable SQLiteDatabase RestorableSQLiteDatabase is a wrapper to replicate android's SQLiteDatabase class with restoring capability. This wrapper ma

Navid 21 Oct 21, 2022
A simple NoSQL client for Android. Meant as a document store using key/value pairs and some rudimentary querying. Useful for avoiding the hassle of SQL code.

SimpleNoSQL A simple NoSQL client for Android. If you ever wanted to just save some data but didn't really want to worry about where it was going to b

Colin Miller 389 Sep 25, 2022