Everything you need to know about Firebase Realtime Database📊
Firebase Database is a product that will make you love Firebase. It is a cloud database for your mobile and web applications. You can save and retrieve data from Firebase Database by using the API’s provided by Firebase and can be used in many technologies including Android.
If you are wondering about Firebase:
I have explained everything regarding the Firebase Realtime Database, starting from the JSON to the deletion of an object from the database. Please follow along:
Here of table of content and what you will learn from this article:
- What is Firebase Realtime Database
- A little bit about JSON Structure
- What are Firebase Realtime Database Rules?
- How to connect to Android App to Firebase Realtime Database?
▪️ Connecting your android app to Firebase
▪ Connecting your app to Firebase Realtime Database - Writing Data to Firebase Realtime Database
- Reading Data from Firebase Realtime Database
- Deleting Data from Firebase Realtime Database
In this tutorial, I have completely described about Firebase Realtime Database, but there is also another database provided by Firebase as well, called Fire Store.
You can read all about that on my blog:
What is Firebase Realtime Database?
The definition of Firebase Realtime Database could be:
Firebase Realtime Database is a cloud-hosted NoSQL Database, which can be accessed and used by Android, iOS and Web app. It stores data in JSON format and any modification made by any platform will be reflected in all connected clients.
In other words, Firebase Realtime uses JavaScript Object Notation JSON to store and retrieve data, which means it contains no tables like structure like SQL but keys and values; these values can contain other keys and values and so on.
Firebase Realtime Database also provides other necessary services like defining rules for your database, making a backup and see the usage.
A little about JSON Structure
All of the Firebase Realtime Database data is stored in a big JSON tree, which can contain JSON Objects in JSON Objects, Array and values a lot more. JSON Object always starts with “{” and end with “}”, for example:
The above image contains a JSON object thus starting with { (left braces), inside that JSON Object there is another JSON Object named “demo”, inside demo the value 123 assigned to “Test” variable and “Value 2” assigned to “Test 2” variable.
This is how JSON works and the Firebase Realtime Database uses this mechanism to store data.
Let me clarify to you with an example. I have written code (also explained below) which is creating a database like this in Firebase Realtime Database
And when I click the three dots in the top right and hit “Export JSON” option:
And this is how the exported JSON file looks like:
Did you find it similar to the previous screenshot? Yes, it is exactly that one!
I hope you know you have a clear understanding of what is Firebase Realtime Database works with JSON.
What Are Firebase Realtime Database Rules?
Afterall Firebase Realtime Database is a Database, and you should be very careful regarding its security.
So, Firebase provided a very clean interface in this regard. You can see a tab named “Rules” in the Firebase Realtime Database window.
Just open that tab and you can type the rules the way that suits. Some sample rules are as below:
- Default Rule 😏
By default, all rules are set in such a way that no-one can read or write to your database. The database can be accessed from Firebase Console only.
- Public Rule 😱
It means anyone can access your database. It is very risky and you should not move to the product with these rules. Must update them before rolling out for production
- User Rule 😍
This is a very common scenario, where users have access to their private data only. When a user is authenticated using Firebase Authentication, it’s given a unique ID called UID. And when some data is generated by the user, it is stored under that UID node. So the following rule makes sure that every user has access to his private data only.
You can learn more about Firebase Realtime Database rules if you want to code real complex rules.
How to Connect the Android project to Firebase Realtime Database?
Okay, so now you have a little know-how of Firebase Realtime Database features and structure. So it’s time to start writing and reading your data to Firebase Realtime Database.
First thing first, you need to connect your Android app to Firebase, and for that, you need a Google account.
There are two ways to connect your project with Firebase.
One is manual; which means you have to manually add the dependency into Android Studio and manually adding an app to Firebase Console.
The other is using Plugin, it is provided by Firebase and pre-installed in the latest versions of Android Studio, and does pretty much automatically.
We will use the plugin, but if you want to dive deep into how this plugin does this; you should connect using the manual way
Connecting your app to Firebase
Here is how you can connect your project to Firebase
- Open Android Studio
- Create a new Project
- Select any pre-defined templates; I am going with Empty Activity. Hit Next.
- Configure your project by providing App Name, Package Name, Save Location, Language and Minimum API Level - for the demonstration purpose; I am leaving everything default. And hit Finish.
- It will take a few moments to do a new project for you. When completed, go to the Tools menu, and select Firebase
- It will open a pane on the right side, where many of Firebase Products will be mentioned, but we are interested in Realtime Database only, so we will expand that and click “Save and retrieve data.“
- Now the first step you will see is “Connect your App to Firebase” with a button “Connect to Firebase”; hit that. You need to be signed in to Android Studio with your Google account, or Android Studio will divert you to chrome (or any default browser) to log in first.
- After logged in, a dialogue will be shown asking if you want to connect your app to an existing project or you can create a new project. After you chose any of them, hit Finish. Now, Android Studio, will add Firebase dependencies to your project and sync it. It can take a few minutes. Once completed, your project will be connected to Firebase
Connecting Your App to Firebase Realtime Database.
Now that your project is connected to Firebase connecting to Firebase Realtime Database is very easy.
The assistant pane — where you connected your app to Firebase — contains a button “Add the Realtime Database to your App” just click that and your app will be connected to Firebase Realtime Database of that particular project that you choose/made for this app.
Writing Data to Firebase Realtime Database
After everything is set up, you can now start writing code to save and retrieve data from Firebase Realtime Database.
The first thing that you need to perform any kind of operation is the instance of the Database. This is quite easy, all you need to do is write the following code and you will have the instance to Firebase Realtime Database.
Now that you have an instance of Database, you need a reference where you want to store your data. You can think of a reference as a path too. By using the following line of code, you will have the reference of the root node of the entire Firebase Realtime Database — the one at the top of JSON Tree.
You can provide any node name to the above getInstance() method, if that node exists; it will return its reference. If not, then a new node with that given string argument will be created.
After getting the reference to the place where you want to write your data, you can start writing it. There are multiple ways to write data to a reference.
Writing a value to the root node in the Firebase Realtime Database
If you just call setValue() function to the reference we created above then it will change the value of the root node, i.e. using this code snippet:
You will get something like this in the Firebase Console:
As in this case, our reference was pointing to the root node so setValue() function changed the value of that. Similarly, we can change the value of any node by getting its reference.
If you want to listen to the results of the writing (setting Value) task that you performed to confirm either the values were written on not, then that’s very simple.
The setValue() function returns a Task class object, so you can save that object, or you can simply call addOnCompleteListener() and listen to the results as below:
Creating a child in Firebase Realtime Database
It’s not very usual that you need just to need to write one value to Firebase Realtime Database and retrieve it, like if you set a value to the root node, then that node can not contain anything else but that value. So we don’t want to write the value to that root node and end the capability of expanding it, but we create its children and set the value to those children. It can contain multiple children; here is how we do that:
This is how it will be shown in the Firebase Console:
The child method returns the reference, so we called a setValue() function on that reference which created that child and set its value. If that child already exists, then its value will be updated. And again, as we called setValue() function, we already now that it returns Task object, so we can perform a check here too regarding the results of the creation of the child.
Writing an object to Firebase Realtime Database
There will be cases when you can no more write the values separately to Firebase realtime database like you want to put the data of user into Firebase Realtime Database, so you won’t be calling setValue() function for each of users attribute. Firebase already aware of this situation, they provide the exact interface to handle this situation.
You can create a class with public getter and setters along with a default constructor (which takes no argument) and push that class object straight into Firebase Database.
For example, I have created this User class with public constructor, getter and setters
I intentionally create the following Date class to store the Date of Birth of the user, this is not a good way to store data, but it’s okay for the demonstration purpose
Okay so now, I can create an object of User class, set the values and I can write it to firebase realtime database with following code snippets
This is how it will be stored in Firebase Realtime Database:
It created another JSON object for the date class object and assigned the values. This is how we can store objects in an object to Firebase Realtime Database.
Possibilities are endless, you can create any type of complex data for your app, but no only you should know how to write databases but also how to read from the database. And that’s exactly what our next step is.
How to Read Data from Firebase Realtime Database.
Reading and writing are of equal importance, if you know how to write data but don’t know how to read, then there is no use of writing it. So I will show you how you can read data from Firebase Database, it is quite easy.
As I mentioned earlier, either you want to read or write, you definitely need Database reference and for that, you need the instance of Database, so go ahead create those first.
Learn what is Firebase Storage and how you can benifit from it:
Reading Single value from Firebase Realtime Database
Now, I am going to read the value of this “child 1” from the following database:
And for that, you need a reference pointing directly to the “child 1” node; here is how you create that:
Now, the myRef object contains a reference to “child 1” you can add a listener called addValueEventListener(). Which will be called first, to get the initial value, second when something is changed in that particular database. Here is how you do that
And you will see “I am a child” in a toast message on your android device. And if due to some reason like permission denied or no internet connection, onCancelled will be called and you can get the error message by using the above code.
How to read an object from the Firebase Realtime Database
As writing each value separately is a tedious task, the same is the case with reading. Firebase provided the interface for reading a whole JSON object at once; here is how you can do that.
You need a reference for sure, so get a reference to your object first. I am going to read the User object that we wrote to Firebase Database earlier:
Here is the complete code of reading a whole object from Firebase Realtime Database:
It is very simple and easy interacting with Firebase Realtime Database. The best part: if your app is closed by the user and some data is changed in the Firebase Realtime Database through Firebase console or any other client; even then the above onDataChange will be called, so if it is a chat application that you are building then you can notify the user that a new message has arrived.
Reading Multiple Child from Firebase Realtime Database
There could be many cases when we need to go through all the children in order to find the one we are interested in. Here I am going to show how you can read multiple child nodes from Firebase Realtime Database.
To read multiple children; we first need to create them. I run this loop to create multiple children with User class objects and to differentiate, I added a value of “i” (loop iteration variable) at the end of each value of the User class object.
Running this code will create multiple child nodes in Firebase Realtime Database as below:
Now, the process of reading one node or multiple is pretty much the same.
I will call addValueEventListener() to the reference object of the root node. This will provide me with a DataSnapshot; now this dataSnaphot object contains all the child nodes.
I will call getChildren() method to get each child starting from the first one, I put it in an enhanced for loop and get all child one by one. Like this:
This is how you can read data from multiple child nodes. Now the next topic is how to Delete Data from Firebase Realtime Database
Deleting Data from Firebase Realtime Database
At once point or another, you must need to delete a certain node or value from your realtime database. Here is how you can do that:
Again, performing any option you need a reference, and a simple function named removeValue() to remove that node regardless of sie of the node. It will be deleted if it contains any mode descendent node; all of those will be deleted as well.
I am going to delete the User0 from the database that we previously created using a loop. Here is the code snippet:
The removeValue() function also returns a Task class object on which you can call the listeners to check either the delete was successful or not.
I am very hopeful that you have learned at least something out of this tutorial and my hard work will surely pay off.
You can learn more about Firebase on my blog:
Learn how to force users to update their app using Firebase Remote Config: