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

12. Introduction to Firebase Realtime Database
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

Having a central place for storing application data is a common requirement for mobile applications. Let’s say you’re building a mobile game and you need to save user progress. You can save it locally on the phone. But what if the user logs in with the same account on a different device? That device doesn’t know that the user has already made some progress and the user will need to start the game all over again. That can lead to unhappy users and bad app reviews.

In this case, you would need to save user progress to a remote database so that users can have access to the data from any number of devices they own. That database is usually hosted somewhere, on the Internet, making it accessible through a simple network connection. This concept is known as the cloud. You can think of the cloud as someone else’s computer, or an entire infrastructure, which you’ve rented for various services.

Firebase Realtime Database is a solution that stores data in the cloud and provides an easy way to sync your data among various devices. It is powered by the Google Firebase platform, and is just a single piece in an otherwise large puzzle. In this chapter, you’ll learn how the Realtime Database works and its key capabilities. Furthermore, you’ll add the Realtime Database to an Android project. Along the way you’ll learn how the Realtime Database takes care of security with database rules, how data is saved to the database and the best practices for data structure.


Firebase Realtime Database is a cloud-hosted database that supports iOS, Android, Web, C++ and Unity platforms.

Realtime means that any changes in data are reflected immediately across all platforms and devices within milliseconds. Most traditional databases make you work with a request/response model, but the Realtime Database uses data synchronization and subcriber mechanisms instead of typical HTTP requests, which allows you to build more flexible real-time apps, easily, with less effort and without the need to worry about networking code.

Many apps become unresponsive when you lose the network connection. Realtime Database provides great offline support because it keeps an internal cache of all the data you’ve queried. When there’s no Internet connection, the app uses the data from the cache, allowing apps to remain responsive. When the device connects to the Internet, the Realtime Database synchronizes the local data changes with the remote updates that occurred while the client was offline, resolving any conflicts automatically.

Client devices access the Realtime Database directly, without the need for an application server. Security rules take care of who has access to what data, and how they can access it. You’ll learn more about security rules later in this chapter.

Firebase Realtime Database is not completely free. There are certain pricing plans. If you want your app to scale you’ll need to pay for the number of connections, disk usage and network usage. You can check out pricing plans on the firebase pricing plans page here:

Realtime Database is a NoSQL database. NoSQL stands for “Not only SQL”. The easiest way to think of NoSQL is that it’s a database that does not adhere to the traditional relational database management system (RDMS) structure. As such, the Realtime Database has different optimizations and functionality compared to a relational database. It stores the data in the JSON format. The entire database is a big JSON tree with multiple nodes. When planning your database you need to keep this in mind to make your database as optimized as possible. You’ll also learn more about data structure and best practices later in this chapter.

Setting up Realtime Database

In Chapter 11, “Firebase Overview,” you added your app to a Firebase project. Now, you need to connect your app to Firebase, to enable its services.


There are few requirements that you need to fulfill in order to setup Firebase with Android.

Connecting the app to the project

Go to the Firebase console and open WhatsUp project that you created.

Registering app

The first step is to register your app. For that, you need two pieces of information. The first one is your app’s package name which you can find in the app-level build.gradle file as applicationId. Enter com.raywenderlich.whatsup as the package name.

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
Alias name: androiddebugkey
Creation date: Oct 26, 2018
Entry type: PrivateKeyEntry
Certificate chain length: 1
Owner: C=US, O=Android, CN=Android Debug
Issuer: C=US, O=Android, CN=Android Debug
Serial number: 1
Valid from: Fri Oct 26 13:29:17 CEST 2018 until: Sun Oct 18 13:29:17 CEST 2048
Certificate finger s:
	 SHA1: A6:72:CD:92:A6:DD:84:31:FA:73:83:48:F6:9D:D4:54:C1:94:07:05
	 SHA256: E0:67:78:A8:38:18:41:35:3B:24:C3:87:01:73:29:BC:A8:55:71:E0:08:00:76:CF:4D:C0:93:38:47:93:FD:54
Signature algorithm name: SHA1withRSA
Subject Public Key Algorithm: 1024-bit RSA key
Version: 1

Downloading config file

Next, you need to download the google-services.json config file by clicking the blue button, and add it to your Android project. Follow the instructions in the console to do that, so that you paste it to the correct location. This file contains your app configuration. If your Firebase configuration changes later you’ll need to download an updated config file and replace the existing one.

Adding Firebase SDK

Next, you need to add the Firebase client libraries to your app. Follow the instructions in the console for this, as well.

Verifying installation

The last step is to verify if everything is set up correctly. For this, you only need to run your app on a device or an emulator. Before you do that, go to the LoginActivity class and uncomment the code. Repeat the process for the HomeActivity and AuthenticationManager classes. Run your app. If everything is set up correctly you’ll get verification message in the console.

Adding Realtime Database

First, you need to create your database in the console. From the menu on the left select Database. Scroll to the Realtime Database section and click the Create database button. The security rules dialog will open:

implementation ''

Database rules

In this section, you’ll be working on WhatsUp app which has an authentication feature so the app can know who your users are. Authentication is the process of verifying users are who they say they are, and to give them certain security access to your service.

  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"

Communication with the Realtime Database

You need a way to talk to the Realtime Database. The first thing you need is a connection. To get a connection you need to create a database reference first. Open RealtimeDatabaseManager class and add the databaseReference property:

private val databaseReference = FirebaseDatabase.getInstance().reference
fun addDummyData() {
    databaseReference.setValue("Saving data on Android")
private val realtimeDatabaseManager by lazy { RealtimeDatabaseManager() }

Data structure

JSON format

As mentioned before, the Firebase Realtime Database stores data in the JSON format. JSON stands for JavaScript Object Notation and it’s a language-independent data format with a minimal number of value types: strings, numbers, booleans, lists, objects, and null. It consists of key/value pairs. The key/value pairs are separated by a colon and each pair is separated by a comma. It is easy for humans to read and write and for machines to parse and generate. This is a sample JSON object:

  "name": "Dean",
  "lastname": "Djermanovic",
  "age": 23,
  "gender": "male"

Best practices for data structure

The entire database is a big JSON tree with multiple nodes. When pushing new data to the database you either create a new node with an associated key or update an existing one. Therefore there is the danger of creating a deeply nested structure. Firebase Realtime Database allows nesting data up to 32 levels deep but that doesn’t mean that this should be the default structure. When thinking about data structure you need to think about how your data is going to be consumed, you need to make the process of saving and retrieving as easy as possible.

  "restaurants": {
    "first_restaurant": {},
    "second_restaurant": {},
    "third_restaurant": {}

Key points

  • To use Firebase Realtime Database in your Android project you need to go through the configuration process first.
  • The Realtime Database provides database rules to control access for each user.
  • Firebase Authentication is very much connected to database solutions Firebase offers, since it controls the access to data, on a per-user-basis.
  • Firebase Realtime Database stores data in JSON format.
  • Because the structure is a JSON, it operates with simple data like numbers, strings, objects, booleans and lists.
  • Firebase Realtime Database data structure should be as flat as possible and designed with scaling in mind.

Where to go from here?

In this chapter, you saw how to configure Realtime Database and what are best practices when it comes to structuring your data. If you want to learn more you can check out official Firebase documentation.

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