Chapters

Hide chapters

Saving Data on Android

First Edition · Android 10 · Kotlin 1.3 · AS 3.5

Before You Begin

Section 0: 3 chapters
Show chapters Hide chapters

Using Firebase

Section 3: 11 chapters
Show chapters Hide chapters

14. Realtime Database Offline Capabilities
Written by Dean Djermanović

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

So far, you’ve created an app that enables you to save posts to the database and read the posts from the database. The next step is to implement offline support. If you turn off your internet connection now and run your app, you’d see an empty screen. That is because your app can’t fetch the data from the database without an internet connection.

One of the most important features of Realtime database is its offline capabilities. If you were creating your own backend system, you would need to persist the data by yourself. Firebase handles that for you, and it enables your app to work properly even when the user loses network connection. In this chapter, you’ll learn how exactly it does that, and you’ll add offline support to your app so that you could see posts on the screen and even add posts while you are offline.

Setting up Firebase

If you skipped previous chapters, you need to set up Firebase in order to follow along. Do the following steps:

  1. Create a project in the Firebase console.
  2. Enable Google sign-in.
  3. Set security rules to the test mode to allow everyone read and write access.
  4. Add google-service.json to both starter and final projects.

If you need a reminder of how to do this, go back to Chapter 11: “Firebase Overview” and Chapter 12: “Introduction to Firebase Realtime Database.”

Be sure to use the starter project from this chapter, by opening the realtime-database-offline-capabilities folder and its starter project from the projects folder, rather than continuing with the final project you previously worked on. It has a few things added to it, including placeholders for the code to add in this chapter.

Enabling disk persistence

Before you start, build and run the starter project, located in the projects folder into realtime-database-offline-capabilities. Make sure you device is connected to the internet. You’ll see your posts on the home screen. Open any post. Now, disconnect your mobile device from the network and navigate back to the home screen. Your posts are still there. By default, Firebase stores your data in-memory. Now, close the app and kill the app process from the Recent apps menu. Run your app again. Now, you’ll see an empty screen.

Caching data locally

To enable disk persistence, you only need one line of code. Open WhatsUpApplication class and enable persistence on the FirebaseDatabase instance in the onCreate method:

override fun onCreate() {
    super.onCreate()
    FirebaseDatabase.getInstance().setPersistenceEnabled(true)
}

Writing data when offline

Disconnect your mobile device from the network and run your app. Add a new post. You’ll see that the post appears on the home screen like it was added to the database. But how is that possible if you are offline?

Keeping data in sync

Realtime database stores a copy of the data, locally, only for active listeners. To understand this, first, delete your app’s data by going to your device’s Settings ▶︎ Apps & notifications ▶︎ WhatsUp ▶︎ Storage and finally tap on the Clear Storage button.

FirebaseDatabase.getInstance().apply {
      setPersistenceEnabled(true)
      getReference(COMMENTS_REFERENCE).keepSynced(true)
}

Other offline scenarios and network connectivity features

Firebase has many features that can help you when offline mode and connectivity are an important part of your app. The features you’re about to learn apply to your app regardless if the local offline persistence is enabled, or not, in your app.

Real-time presence system

The real-time presence system allows your app to know the status of your users — are they online, offline, away, or some other status. This feature is inevitable for chat applications for example, because you want to know if the person you are texting is online. This feature may seem simple, but to build an entire app infrastructure or a mechanism, which handles this for you, can be quite troublesome.

Latency

Generally speaking, latency is the time delay between the cause and the effect of some change. In Realtime database that would, for example, be when a user triggers the action to disconnect from the server until the user is actually disconnected, or the delay between requesting a login entry, to actual authorization response.

Key points

  • Realtime database allows you to enable disk persistence to make your data available when you’re offline.
  • Enabling disk persistence also tracks of all the writes you initiated while you were offline and then when network connection comes back it synchronizes all the write operations.
  • Realtime database stores a copy of the data, locally, only for active listeners. You can use the keepSynced method on a database reference to save data locally for the location that has no active listeners attached.
  • Firebase provides you with the real-time presence system, which allows your app to know the status of your users, are they online or offline.
  • Firebase handles latency in a way that stores a timestamp, that is generated on the server, as data when the client disconnects and lets you use that data to reliably know the exact time when the user disconnected.

Where to go from here?

In this chapter, you learned how Firebase works offline and what features it provides to help you handle offline mode and connectivity issues. You also improved your apps user experience in a way that you enabled your app to work as expected even if the user is not connected to the internet.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now