Android Local Database Tricks with Kotlin and ObjectBox.

Android Local Database Tricks with Kotlin and ObjectBox.

Ryan Godlonton-ShawBlockedUnblockFollowFollowingMar 9For those of you looking for a simple way to store large chunks of JSON data into a local database in Android, then look no further.

There are so many times when we come across offline requirements of accessing big chunks of data from a REST online database and saving it locally for offline use later but do not want to go through with writing excessive and large amounts of boilerplate code to do it and we would like a way to do this simply and most effectively.

Here I present a really simple and easy way to save large data into your local DB without relying on Shared Preferences or the need to do lengthy ORM mapping or creating custom converters for your data classes.

Shared Preferences was one option but it is normally only used for saving small pockets of data like settings — the other downside is that if large data is saved into Shared Preferences it takes a really long time to access the Shared Preferences data again.

So welcome to ObjectBox.

What is ObjectBox?ObjectBox is a really cool super fast object-oriented mobile database that persists objects, built uniquely for IoT and Mobile devices.

It lets you avoid many repetitive tasks and offers a simple interface to your data.

It seems to have been adopted by the Android engineering world really well so far replacing SQLite databases quite rapidly.

Below is a quick and simple solution for developers looking to rapidly setup ObjectBox and also have a way to store data quickly without having to write custom converters for each and every data object in their DB.

So let’s begin — Firstly install ObjectBox.

Add it to your project in your root build.

gradle.

buildscript { ext.

objectboxVersion = ‘2.

3.

3’ respositories { jcenter()}dependencies {// Android Gradle Plugin 3.

0.

0 or later supported classpath ‘com.

android.

tools.

build:gradle:3.

3.

1’ classpath “io.

objectbox:objectbox-gradle-plugin:$objectboxVersion” }}In your app build.

gradle module add this.

apply plugin: ‘com.

android.

application’apply plugin: ‘io.

objectbox’ In your dependencies add this:implementation "io.

objectbox:objectbox-kotlin:$objectboxVersion"implementation "io.

objectbox:objectbox-android:$objectboxVersion"kapt "io.

objectbox:objectbox-processor:$objectboxVersion"Once thats done, we’re going to want to initialize ObjectBox and create a BoxStore reference.

In your Application class write something like this.

import android.

app.

Applicationimport com.

crashlytics.

android.

Crashlyticsimport com.

coolcompany.

coolproject.

model.

ObjectBoximport io.

fabric.

sdk.

android.

Fabricclass MainApplication : Application() { companion object Constants { const val TAG = "myAmazingProject" } override fun onCreate() { super.

onCreate() Fabric.

with(this, Crashlytics()) ObjectBox.

init(this); }}Then in your models create an ObjectBox singleton like so.

import android.

content.

Contextimport android.

util.

Logimport com.

coolcompany.

coolproject.

BuildConfigimport com.

coolcompany.

coolproject.

MainApplicationimport io.

objectbox.

BoxStoreobject ObjectBox { lateinit var boxStore: BoxStore private set fun init(context: Context) { boxStore = MyObjectBox.

builder().

androidContext(context.

applicationContext).

build() if (BuildConfig.

DEBUG) { Log.

d(MainApplication.

TAG, "Using ObjectBox ${BoxStore.

getVersion()} (${BoxStore.

getVersionNative()})") } }}Now you have initialized ObjectBox in your project and will have access to the BoxStore ObjectBox in your project.

Okay now for dealing with your JSON data.

If you do not know how to convert your JSON into data models quickly then please read my article here.

Basically convert your JSON data into Kotlin data models using Pojo Generator.

Once all that is done and your API calls and services are setup and done, create another data class and call it DataObjectBox like so.

import io.

objectbox.

annotation.

Entityimport io.

objectbox.

annotation.

Id@Entitydata class DataObjectBox( @Id var id: Long = 0, var data: String? = null)You can have as many “data” String properties as you like in this class and name them whatever you feel but only one is needed if you have one big payload dump.

The data variable will hold all the data as one long String for the JSON payload.

Now the fun part comes in.

In your Activity.

private lateinit var payloadBox: Box<DataObjectBox?>// inside onCreate add this //payloadBox = ObjectBox.

boxStore.

boxFor()// inside your API call //private fun getJSONData(token:String?) { txtViewProgress.

text="Please wait.

retrieving and saving all data.

" disposable = thisApiService.

getData(token) .

subscribeOn(Schedulers.

io()) .

observeOn(AndroidSchedulers.

mainThread()) .

subscribe( { result -> val gson = Gson() val json = gson.

toJson(result) val payloadData = DataObjectBox() payloadData.

data=json payloadBox.

put(payloadData) txtViewProgress.

text="Completed.

" startActivity(Intent(this, NextActivity::class.

java)) finish() }, { error -> Toast.

makeText(this, error.

message, Toast.

LENGTH_SHORT).

show() } )}As you can see we retrieve the JSON dump, then with the assistance of Gson we deserialize it from its original object into a string and then dump it into the payloadBox data property and viola!.We now have access to that data at anytime in our app.

To access our data again we simply do this.

val box = ObjectBox.

boxStore.

boxFor(DataObjectBox::class.

java)val mypayload=box.

get(1).

datavar payloadDataOriginalObject: ResponseMainDataDTO?.= Gson().

fromJson(mypayload, ResponseMainDataDTO::class.

java)Now whenever you need to play around with the data you have it!(payloadDataOriginalObject) — ResponseMainDataDTO would be your top level data class.

This method alleviates any necessity to write custom converters and Entities for all your data classes — removing the whole ORM mapping process.

Cheerio and happy coding!.

. More details

Leave a Reply