Firebase Realtime Database – Read/Write Data example | Android

Firebase Realtime Database is a cloud-hosted database that helps us to store and sync data with NoSQL cloud database in realtime to every connected client. In this tutorial, we’re gonna look at way to read/write data in an Android App.

More Practice:
Firebase Realtime Database – Get List of Data example | Android
Firebase Realtime Database – Display List of Data with FirebaseRecyclerAdapter | Android

I. Firebase Realtime Database Overview

1. How data is structured

All Firebase Realtime Database data is stored as JSON objects without tables or records. When adding data, it becomes a node in JSON structure. For each node, we can:
– provide our own key (IDs/semantic names), or
– let it do automatically using push() method.

2. Offline Capabilities on Android

Firebase work even if our app temporarily loses internet connection. It provides tools for persisting data locally, managing presence, and handling latency.

2.1 Disk Persistence

When enabling disk persistence that automatically stores the data offline in case of no internet connection. When internet is on, offline data will be pushed to realtime database, even if the user or operating system restarts the app.

We can enable disk persistence with just one line of code:

2.2 Managing Presence

– Firebase provides simple primitives that we can use to write to the database at the time client disconnects from the Firebase Database servers. All write operations, including setting, updating, and removing, can be performed upon a disconnection.

– With Firebase, we also can detect Connection State. It is useful to know when our app is online or offline. Firebase Realtime Database provides a special location at /.info/connected which is updated every time the client’s connection state changes.

2.3 Handling Latency

The Firebase Realtime Database servers provide a mechanism to insert timestamps generated on the server as data with firebase.database.ServerValue.TIMESTAMP.

3. CRUD Operations

We can insert, read, update, delete data from Firebase Realtime Database. By default, these operations access to database is restricted so only authenticated users can read or write data.

II. Way to read/write data

0. Add Firebase to Android App
0.1 Create Firebase Project and Add Firebase Config file

Follow this guide to create Firebase Project and generate google-services.json file and move it into your Android App root directory. You don’t need to get SHA-1 Key in this example.

0.2 Add dependencies

build.gradle (project-level):

build.gradle (App-level):

1. Enable Firebase Auth

By default, only authenticated users can read or write data, so we need Firebase Authentication for next step.
Go to Your Firebase Project Console -> Authentication -> SIGN-IN METHOD -> Enable Email/Password.

To do without setting up Authentication, we can change the rules in the Firebase Console -> choose Project -> Database section on the left -> Rules tab:

2. Get a DatabaseReference

In order to perform any read or write operation to database, we need to get the reference to database first, so Instance of DatabaseReference gives us reference to database JSON node. From here we can to use the child node names to go further:

3. Write Data

We can use setValue() to:
– save data to a specified reference
– replace any existing data at that reference

The data can be:
String, Long, Double, Boolean, Map<String, Object>, List<Object>
– custom Java object (has a default constructor with no arguments and public getters for the properties to be assigned)

4. Read Data
4.1 At a path

Use the addValueEventListener() method to add a ValueEventListener to a DatabaseReference. It has onDataChange() event callback that is called every time data is changed at the specified database reference, including changes to children:

4.2 Once

We can use the addListenerForSingleValueEvent() method to make a callback to be called once and then immediately removed.

For instance, load a user’s profile when he begin send a new message:

4.3 Detach listeners

Callbacks are removed by calling the removeEventListener() method:

Calling removeEventListener() on a parent listener does not automatically remove listeners registered on its child nodes. So we must also call it on any child listeners to remove the callback.

5. Delete Data

– The simplest way is to call removeValue() on a reference to the location of that data.

– We can also delete by specifying null as the value for write operation setValue() method:

III. Practice

1. Goal

We will build an Android App that can:
– create Account, sign in/sign out for Firebase Authentication.
– read/write user and message data to Firebase Realtime Database.

firebase-realtime-db-demo-app

firebase-realtime-db-demo-db

2. Technology

– Gradle 2.3.3
– Android Studio 2.x
– Firebase Android SDK 11.x

3. Project Structure

firebase-realtime-db-structure

LoginActivity is for Authentication, then user can change to MessageActivity to send Message to Firebase Realtime Database.

4. Step by step
4.1 Create Android Project

– Generate new Android Project with package com.javasampleapproach.firebaserealtimedb.
build.gradle (project-level):

build.gradle (App-level):

4.2 Create Firebase Project & Add Firebase Config file

– Follow this guide to generate google-services.json file and move it into your Android App root directory. You don’t need to have SHA-1 Key in this example, just leave it blank.

– Make sure that package_name in google-services.json has a correct value according to:
+ applicationId in build.gradle (App-level).
+ package in AndroidManifest.xml.
In this case, it is com.javasampleapproach.firebaserealtimedb.

firebase-realtime-db-add-app

4.3 Enable Firebase Auth

Go to Your Firebase Project Console -> Authentication -> SIGN-IN METHOD -> Enable Email/Password.

4.4 Model

4.5 LoginActivity

To know how to implement Firebase Authentication App Client, please visit:
Firebase Authentication – How to Sign Up, Sign In, Sign Out, Verify Email | Android

In this tutorial, we don’t explain way to authenticate an user again.

4.6 MessageActivity

4.7 Android Manifest

4.8 Run & Check result

– Use Android Studio, build and Run your Android App:

firebase-realtime-db-result-app

– Open Firebase Project Console -> Database:
firebase-realtime-db-result-db

III. Source code

FirebaseRealtimeDB


Related Posts



Got Something To Say:

Your email address will not be published. Required fields are marked *

*