Caching Solutions

Discover how to improve user experience by implementing offline support in this chapter.

We'll cover the following

This lesson explains the different options available on Android to cache the data for offline support.

Preferences

One of the most common ways to persist data on the Android phone is to use SharedPreferences.

The shared preference is basically a key-value store solution for a small amount of data with a built-in memory cache. We have already used shared preferences to persist in the login state.

Files

When the data is too big for the shared preference, we can always use plain old files.

val filename = "myfile.txt"
val fileContents = "Hello world!"
openFileOutput(filename, Context.MODE_PRIVATE)
        .write(fileContents.toByteArray())

The problem with files is that we need to convert our data to a format that can be stored and reconstructed later, such as a JSON string, which is not efficient in some cases.

SQLite

Fortunately, in Android, we can create a local database called SQLite.

The android.database.sqlite package contains all sorts of API to work with databases - from simple queries to complicated joins. While the Android SQLite package contains everything we need, the API is pretty basic and requires us to write a lot of boilerplate code. For these reasons, Google decided to write an abstraction on top of the android.database.sqlite package to make it easier to work with a database.

This layer is available as a separate library called Room. In the next lesson, we are going to learn how to use the Room database to store and access blog articles.

Get hands-on with 1400+ tech skills courses.