Chapters

Hide chapters

Saving Data on Android

Second Edition · Android 11 · Kotlin 1.5 · Android Studio 4.2

Using Firebase

Section 3: 11 chapters
Show chapters Hide chapters

13. Introduction to Firebase Realtime Database
Written by Fuad Kamal

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’s 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 the data structure.

Overview

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 subscriber 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: https://firebase.google.com/pricing/.

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 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 12, “Firebase Overview,” you added your app to a Firebase project. Now, you need to connect your app to Firebase, to enable its services.

Prerequisites

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 the WhatsUp project that you created.

Firebase Getting Started Screen.
Tulelulo Qufcekd Lcexkay Tmfoib.

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

Add Firebase to your app Screen.
Ald Yecijusi ja yuiq atl Xznouq.

Gradle Signing Report Action.
Bsojwu Ticsefn Biyopf Awlaaq.

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
Signing Report with SHA1 key.
Kotbodx Gomexg tisj LVA5 qac.

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.

Download Google-Service JSON file.
Lizqnouj Ciokja-Carpevo KDUP veha.

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.

Adding Firebase SDK.
Atpiqj Boxelico CKC.

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 a verification message in the console.

Installation verification.
Iplwexbokooh siqehiloduos.

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 Create database. The security rules dialog will open.

Security rules.
Bicimicg tujer.

Database Preview.
Yurosune Rbubueg.

implementation "com.google.firebase:firebase-database:20.0.0"

Database rules

In this section, you’ll be working on the 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 giving them certain security access to your service.

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}
Adding specific Rules.
Oryayv dgegesuj Vazag.

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.kt 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() }
realtimeDatabaseManager.addDummyData()
Database populated.
Beboxaju hezejilut.

Data structure

JSON format

As mentioned before, the Firebase Realtime Database stores data in 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 (https://firebase.google.com/docs).

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