Firebase Realtime Database Integration in Android 2

This tutorial describes the usage of the Firebase Realtime Database service in Android. If you don’t know what is Firebase and how to setup in android studio, then please through this previous blog.

So lets starts with Realtime Database service:

To write your Firebase Realtime Database service, use the FirebaseDatabase API. The instructions in this page assume that you have completed the steps for adding Firebase to your Android project.

Why Firebase Realtime Database?

The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client.

Realtime: Instead of typical HTTP requests, the Firebase Realtime Database uses data synchronization—every time data changes, any connected device receives that update within milliseconds. Provide collaborative and immersive experiences without thinking about networking code.

Offline: Firebase apps remain responsive even when offline because the Firebase Realtime Database SDK persists your data to disk. Once connectivity is reestablished, the client device receives any changes it missed, synchronizing it with the current server state.

So, in this tutorial we will so how to integrate the realtime database in our android app and we will see how to perform CRUD operations on this database with the simple To-do app.

Set up Firebase and the Database SDK

In Android Studio, add the database dependency to your app-level build.gradle file:

Configure Firebase Database Rules

The Realtime Database provides a flexible, expression-based rules language, called Firebase Realtime Database Security Rules, to define how your data should be structured and when data can be read from or written to. When integrated with Firebase Authentication, developers can define who has access to what data, and how they can access it.

By default, your database rules require Firebase Authentication and grant full read and write permissions only to authenticated users. So we stick to this default rules. For more details read here.

Structure Your Database

All Firebase Realtime Database data is stored as JSON objects. You can think of the database as a cloud-hosted JSON tree. Unlike a SQL database, there are no tables or records. When you add data to the JSON tree, it becomes a node in the existing JSON structure with an associated key. You can provide your own keys, such as user IDs or semantic names, or they can be provided for you using push(). For more details read here.

Below is the sample json data structure of our simple To-do app.


We need request for internet permission.

Get Firebase Instance

Obtain the FirebaseDatabase instance.

Save Data on Android

There are four methods for writing data to the Firebase Realtime Database:

Method Common uses
setValue() Write or replace data to a defined path, such as users/<user-id>/<username>.
push() Add to a list of data. Every time you call push(), Firebase generates a unique key that can also be used as a unique identifier, such as user-posts/<user-id>/<unique-post-id>.
updateChildren() Update some of the keys for a defined path without replacing all of the data.
runTransaction() Update complex data that could be corrupted by concurrent updates.

Write, update, or delete data at a reference

Basic write operations

For basic write operations, you can use setValue() to save data to a specified reference, replacing any existing data at that path. You can use this method to:

  • Pass types that correspond to the available JSON types as follows:
    • String
    • Long
    • Double
    • Boolean
    • Map<String, Object>
    • List<Object>
  • Pass a custom Java object, if the class that defines it has a default constructor that takes no arguments and has public getters for the properties to be assigned.

If you use a Java object, the contents of your object are automatically mapped to child locations in a nested fashion. For example, our To-do app, Items object might look as follows:

You can add a todo item with setValue() as follows:

Using setValue() in this way overwrites data at the specified location, including any child nodes.

Append to a list of data

Use the push() method to append data to a list in multiuser applications. The push() method generates a unique key every time a new child is added to the specified Firebase reference. By using these auto-generated keys for each new element in the list, several clients can add children to the same location at the same time without write conflicts. The unique key generated by push() is based on a timestamp, so list items are automatically ordered chronologically.

Update specific fields

To simultaneously write to specific children of a node without overwriting other child nodes, use the updateChildren() method. When calling updateChildren(), you can update lower-level child values by specifying a path for the key.

So our modified Items class to get hashmap data.

To create a new item and update it to the user todo items list:

Delete data

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

Retrieve Data

Firebase data is retrieved by attaching an asynchronous listener to a FirebaseDatabase reference. The listener is triggered once for the initial state of the data and again anytime the data changes.

Listen for events

You can listen for these types of events that retrieve data:

Listener Event callback Typical usage
ValueEventListener onDataChange() Read and listen for changes to the entire contents of a path.
ChildEventListener onChildAdded() Retrieve lists of items or listen for additions to a list of items. Suggested use with onChildChanged() andonChildRemoved() to monitor changes to lists.
onChildChanged() Listen for changes to the items in a list. Use withonChildAdded() and onChildRemoved() to monitor changes to lists.
onChildRemoved() Listen for items being removed from a list. Use withonChildAdded() and onChildChanged() to monitor changes to lists.
onChildMoved() Listen for changes to the order of items in an ordered list.onChildMoved() events always follow theonChildChanged() event that caused the item’s order to change (based on your current order-by method).

Value events

You can use the onDataChange() method to read a static snapshot of the contents at a given path, as they existed at the time of the event. This method is triggered once when the listener is attached and again every time the data, including children, changes.

Child events

Child events are triggered in response to specific operations that happen to the children of a node from an operation such as a new child added through the push() method or a child being updated through the updateChildren() method.

The onChildAdded() callback is triggered once for each existing child and then again every time a new child is added to the specified path.

The onChildChanged() callback is triggered any time a child node is modified.

The onChildRemoved() callback is triggered when an immediate child is removed.

The onChildMoved() callback is triggered whenever the onChildChanged() callback is triggered by an update that causes reordering of the child.

Detach listeners

Callbacks are removed by calling the removeEventListener() method on your Firebase database reference.

Note: Calling removeEventListener() on a parent listener does not automatically remove listeners registered on its child nodes; removeEventListener() must also be called on any child listeners to remove the callback.




View Database in the Dashboard

You can access this data in the Firebase console as follows:

  1. In the Firebase console, open your project.
  2. Select Database from the menu to view the Realtime Data dashboard.


Sample Code



I hope you will like the article and it will definitely help you to make your apps more productive. In case of any confusion or query, feel free to ask. And if you found this tutorial to be useful, Share with others.

About Durga Chiranjeevi

I’m a normal guy, engineer by education who is passionate about Programming and Internet. An android enthusiast, now moving for cross platforms and game development.