Home Android & Kotlin Books Saving Data on Android

15
Realtime Database Offline Capabilities Written by Harun Wangereka

Heads up... You're reading this book for free, with parts of this chapter shown beyond this point as scrambled text.

You can unlock the rest of this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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 because your app can’t fetch the data from the database.

One of the most important features of the Realtime Database is its offline capabilities. If you were creating your 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 to follow along. Do the following steps:

  1. Create a project in the Firebase console.
  2. Enable Google sign-in.
  3. Create a new Realtime Database. Set security rules to the test mode to allow everyone read and write access. You should never use these settings for your production apps.
  4. Add google-service.json to both starter and final project’s root directory.

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

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

Enabling disk persistence

Before you start with coding, build and run the starter project. Make sure your device is connected to the Internet.

The sign in screen.
Yzi jenf oc dgdioq.

The screen with all saved posts.
Zje xlwiat semp okv qatur biffk.

Empty posts screen.
Izgvk pasbl bfbauv.

Caching data locally

To enable disk persistence, you only need one line of code. Open WhatsUpApplication.kt and add the following at the end of onCreate():

FirebaseDatabase.getInstance().setPersistenceEnabled(true)
The screen with all saved posts.
Kwu fcteof fojn uvl rorid lorfk.

Writing data when offline

To test this case, disconnect your mobile device from the network and create a new post with the text “Newly added post to test persistence.”. You’ll see that the post appears on the home screen.

The post is added offline.
Ndo pegn us ipheh eqcyemi.

The post isn't added to the database.
Hhe fijt ebr'n ajric nu vva fesiwuna.

The post is visible in the database.
Jwu hodj aw yexiyta os gya joyuviki.

Keeping data in sync

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

const val COMMENTS_REFERENCE = "comments"
FirebaseDatabase.getInstance().apply {
      setPersistenceEnabled(true)
      getReference(COMMENTS_REFERENCE).keepSynced(true)
}
The post presenting comments when offline.
Gpa juvl rpexekxahx yosbehmx bqeq uyxbavo.

Querying Offline Data

With persistence enabled, Firebase Realtime Database stores result from queries done when the app doesn’t have an active network connection. The queries are done on data that has been previously loaded. It firsts loads data from the cache. Then, once your app is connected to the Internet again, it loads the data from your query. A query can return some items while offline. Then when online, more items will be added to your query results.

Other offline scenarios and network connectivity features

Firebase has many features that can help you when in 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.

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’re 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 be, for example, when the user triggers disconnecting from the server until the disconnecting action is done, or the delay between requesting a login entry, to an 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 all the writes you initiated while you were offline and then when the 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 keepSynced() on a database reference to save data locally for the location that has no active listeners attached.
  • You can be able to query data that is available offline. Realtime Database syncs once the app is online to provide more query results.
  • Firebase provides you with a 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 app’s 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.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC

You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

Unlock Now

To highlight or take notes, you’ll need to own this book in a subscription or purchased by itself.