Creating a Real Time Database with Firebase on Android

Connecting your Android app to the cloud is always a daunting task! If you don’t have an SQL database background, storing data in the cloud will seem near impossible. Even if you have background knowledge of SQL, setting up servers, maintaining connections, and monitoring interactions is a headache.

Lucky for us Android developers, Google’s very own Firebase has an API called the Firebase Database, which is a real-time, super secure database that will only take you about a day to understand.

What is Firebase Database?

According to the docs:

The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client…all of your clients share one Realtime Database instance and automatically receive updates with the newest data.

Essentially, Firebase lets you create and manage your own database right from the online firebase console. The best part? You don’t need to know a thing about SQL. You can easily store strings, lists, or any other values as a special file called JSON in the database. This is a bit different from Firebase Cloud Storage  (Millibit Tutorial) which deals with storing media such as images, videos, or files. The Firebase Database is generally used for real-time updates between the app and server (and vice versa).  In this tutorial, we’ll go through the step-by-step process of uploading and downloading data to and from the Firebase Database.

Goal: Create an app that can store and retrieve a user’s password in the Firebase Database.

This tutorial will have two parts. In part one, we will explore how to store values in our Firebase Database and in part two, we will retrieve values from our Firebase Database. But first, we need to set up Firebase Database in our project!

 

In Android Studio, head over to tools ->Firebase, and then go to Real-time Database. Hit “add the Real-time Database” in the assistant, and Android Studio will implement the library for you. 

That’s literally it. Android Studio has now set up the dependencies for the Firebase Database library! Now head over to your web browser, and in your Firebase console, go over to “Database” and hit “Get Started”.

When you click “Get Started”, you’ll see your database in the Firebase console. Right now, it should be empty—lets put something in it!

 

Before we get started, it’s important to understand how the database is structured. I like to imagine it as a tree. Basically, at the top of the tree you have your database reference. Then, under this main reference, you can store children and sub-children. At the end of the day, you are storing either a String,Long,Double,Boolean,Map<String, Object>, or List<Object>. Here’s an illustration to make this easier to understand:

So lets first start with the very beginning; the Firebase Real-Time Database is centered around the object DatabaseReference. This object will reference your database and let you add/delete/modify data and children. Let’s create it:

DatabaseReference mRef;
mRef = FirebaseDatabase.getInstance().getReference();

This mRef object is like the very top reference as shown in the illustration above:

Now that we have this reference, we can create children under it and add some data!

    mRef.child("users").child(userName).child("password").setValue(userPass);

Boom. That’s it. In literally three lines of code, we were able to store a user’s data in our Firebase database. Now, go back into your firebase console and look at the data that appears. It should look something like this (assuming userName = “ruchir” and userPass = “millibit”)

APP NAME-ID 
 +-- users
   |  
   |-- ruchir
       |
       +--password
          |
          +--millibit

This file tree should have updated in your firebase database just like that in real time!

 

Okay, so there are two really useful techniques to retrieve from the database. First is through a callback and second is through a one-time receiver.

  1. Event Callback: This method is useful for if you want to receive an update from the database as soon as a value changes. For example, if you are making a chat app (which you should NOT USE FIREBASE REAL-TIME DATABASE FOR, this is just an example) and you want to notify the second device whenever a new message comes in, you can set this dataChange listener, and it will automatically be called (assuming it has internet connection) whenever data is changed in the location of mRef.
ValueEventListener postListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        // Get Post object and use the values to update the UI
        Object valueThatChanged = dataSnapshot.getValue();
        DatabaseReference locationChanged = dataSnapchot.getRef();
        
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
};
mRef.addValueEventListener(postListener);

There are actually quite a few of these kinds of callbacks—

onCancelled(DatabaseError error) 

onChildAdded(DataSnapshot snapshot, String previousChildName)

onChildChanged(DataSnapshot snapshot, String previousChildName)

onChildMoved(DataSnapshot snapshot, String previousChildName) 

onChildRemoved(DataSnapshot snapshot) 

Awesome! Now you can upload to the Firebase Real-time Database, and immediately be notified whenever something changes in your database.

Challenge Problem: Send a message from one phone to the other using the Real-Time Databse. Process: Create an app with two modes. Detection mode, which should contain a valueEventListener and display any database changes on screen, and send mode, which should be able to upload a string that the user types into an edittext to the database.. Download the app on two different phones and open send mode on one phone and detection mode on the other. Send a message from the send mode and see if it appears on the other device!

 

2. One-time Receiver: This method is useful if you want to grab a value from your database anytime on command, without necessarily having to wait for any callbacks.

mRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        Object valueThatChanged = snapshot.getValue();
        DatabaseReference locationChanged = snapshot.getRef();
    }
}

Firebase has done a very bad job of creating this function, and I strongly disagree with the fact that it is called a listener. Instead, it should be called a retriever and just operate as a simple getter method that returns a snapshot. When I first learned about the SingleValueEvent listener, I was confused out of my mind, so just remember, this listener only is called once; it’s basically a getter method.

That’s it!

You’ve just created your own database, uploaded data to it, and even downloaded data from it. This would’ve taken months to set up if we were trying to create our own infrastructure, but luckily, it can be done in just a few hours with Firebase. As usual, let me know if you ahve any questions or concerns in the comments, and I’ll be more than happy to help.

 

Please check out my other apps here.