Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Firebase Database Tutorial

Firebase Database Tutorial

Hello Developers, in this tutorial we are going to discuss Firebase Database. Earlier we had covered android tutorials on how to save data in Android SQLite Database as well as Creating and Storing Data on a Live Server using PHP and MySQL database for our backend. We will create a Grocery List App using Firebase Database for storage for this Android Firebase Database Tutorial.

Firebase Database, also called as Firebase Realtime Database is used to store and sync data using a cloud-based NoSQL database. Data present in your Firebase Database can be synchronized across multiple platforms like android, ios and web and across many clients in real-time.

Firebase Database supports offline capabilities also to retain the data once your device is offline. In Firebase Database the data is stored as JSON Nodes. The Firebase Realtime Database Security Rules, determines the structure of your data and set the read and write access permissions.

Creating Firebase Database

To create a database using Firebase Database follow the below steps :

  1. Go to Firebase Website and create a firebase account to start with. Go to Firebase console and Create a New Project by clicking on the “Create New Project” Button as shown below.
  2. Give the Project name and country you are currently in, Once you are done click on “Create Project” button.
  3. In the next screen choose “Add Firebase to your Android app” and then add the package details and Debug signing certificate SHA-1 key( This is required if you want to enable certain features like Dynamic Links, Invites, and Google Sign-In etc. otherwise it is an optional field). If you are not sure how to generate SHA-1 fingerprint see the following tutorial Adding Google Login to Android Apps under the heading Generate SHA-1 fingerprint
  4. This will download the google-services.json file. Download it to your computer. We will add it to our android app later.

  5. In the project’s dashboard. Click on Auth Menu, then in the SIGN-IN METHOD click on Email/Password and enable it.

This is required because the default security rules for the Firebase Database allows only authenticated users to read and write to the Firebase Database.

Then click on the Database tab in the Firebase Menu.

It shows the root of the JSON tree, we would be adding a child node called listItems and then will add each item under it. When we add data to the JSON tree, it becomes a new node in the existing JSON structure with an associated key.

You can check the Rules tab to see or change the security rules for reading and writing on Firebase Database. Below figure shows the default settings.

You can change these to true, if you want free unauthenticated access to your Firebase Database. Once you are done with this, Let’s create our Grocery Application that will connect to Firebase Database we have just created and uses Firebase Authentication that we have enabled in the console.

Pre-requisites for Firebase Database Tutorial

  1. Android Studio installed on your PC (Unix or Windows). For working with Firebase you should install Android Studio 1.5 or higher. You can learn how to install it here . Also download the latest Google Play services SDK from through Android SDK Manager.
  2. A real time android device (Smartphone or Tablet) configured with Android Studio. . The device should be running Android 2.3 (Gingerbread) or newer, and Google Play services 9.2.0 or newer.
  3. Take a look at the Android RecyclerView Tutorial if you are unaware of the concepts, since we will be using recyclerview to list the items in our app.
  4. Important : Before Proceeding any further please go through the Firebase Authentication Tutorial as we will be reusing the same code here to authenticate the user, before he can write or read from the database

Creating a New Project

  1. Go to File → New → New Project and enter your Application Name.
  2. Enter company domain, this is used to uniquely identify your App’s package worldwide. Remember to use the same package name as used in the firebase console.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish. We have used the Activity Name as ListItemsActivity, we will be using this activity for listing the Grocery Items.

Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.

Add Permissions and Dependencies

  1. After Gradle syncs the project, add the google-services.json file to your project’s app folder as shown below.
  2. Since we need to connect to the Network add the Internet permission in AndroidManifest.xml file.
  3. AndroidManifest.xml

  4. Now open your project’s build.gradle from the project’s home directory and add the following dependency.
  5. build.gradle

    	classpath ''
  6. Next, open your app’s build.gradle from the and add the following at the end.
  7. build.gradle

    	apply plugin: ''
  8. Also add the following dependencies in the dependencies section.
  9.     compile ''
        compile ''
        compile ''
        compile ''

Working with Firebase Database

Create a Java class which will act as a model class for the grocery items that we will add to our database.

package com.androidtutorialpoint.firebasegrocerylistapp;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ListItem {

    public String listItemText;
    public String listItemCreationDate;

    public String getListItemText() {
        return listItemText;

    public void setListItemText(String listItemText) {
        this.listItemText = listItemText;

    public void setListItemCreationDate(String listItemCreationDate) {
        this.listItemCreationDate = listItemCreationDate;

    public String toString() {
        return this.listItemText +"\n" + this.listItemCreationDate;

    public String getListItemCreationDate() {
        return listItemCreationDate;

    public ListItem() {
        // Default constructor required for calls to DataSnapshot.getValue(ListItem.class)

    public ListItem(String listItemText) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
        this.listItemCreationDate = sdf.format(new Date());
        this.listItemText = listItemText;

    public Map toMap() {
        HashMap result = new HashMap();
        result.put("listItemText", listItemText);
        result.put("listItemCreationDate", listItemCreationDate);
        return result;


We have two fields listItemText and listItemCreationData and we have defined the getters and setters method for the same. Additionally, we have defined a utility method toMap() that will be used while writing the items to the database.

Add the following code to and then we will explain the complete functionality step by step.

package com.androidtutorialpoint.firebasegrocerylistapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ListItemsActivity extends AppCompatActivity {

    private final String TAG = "ListActivity";
    DatabaseReference mDB;
    DatabaseReference mListItemRef;
    private RecyclerView mListItemsRecyclerView;
    private ListItemsAdapter mAdapter;
    private ArrayList myListItems;

    public void onCreate(Bundle savedInstanceState) {


        mDB= FirebaseDatabase.getInstance().getReference();
        mListItemRef = mDB.child("listItem");
        myListItems = new ArrayList();
        mListItemsRecyclerView = (RecyclerView)findViewById(;
        mListItemsRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
        mListItemsRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        Toolbar toolbar = (Toolbar) findViewById(;
        FloatingActionButton fab = (FloatingActionButton) findViewById(;
        fab.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

        mListItemRef.addChildEventListener(new ChildEventListener() {
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {


            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            public void onChildRemoved(DataSnapshot dataSnapshot) {

            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            public void onCancelled(DatabaseError databaseError) {

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, menu);
        return true;

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
                startActivity(new Intent(this, LoginActivity.class));
        return super.onOptionsItemSelected(item);

    public void createNewListItem() {
        // Create new List Item  at /listItem
        final String key = FirebaseDatabase.getInstance().getReference().child("listItem").push().getKey();
        LayoutInflater li = LayoutInflater.from(this);
        View getListItemView = li.inflate(R.layout.dialog_get_list_item, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

        final EditText userInput = (EditText) getListItemView.findViewById(;

        // set dialog message
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // get user input and set it to result
                        // edit text
                        String listItemText = userInput.getText().toString();
                        ListItem listItem = new ListItem(listItemText);
                        Map listItemValues = listItem.toMap();
                        Map childUpdates = new HashMap();
                        childUpdates.put("/listItem/" + key, listItemValues);



    public void deleteAllListItems(){
        Toast.makeText(this,"Items Deleted Successfully",Toast.LENGTH_SHORT).show();

    private void fetchData(DataSnapshot dataSnapshot) {
        ListItem listItem=dataSnapshot.getValue(ListItem.class);

   private void updateUI(){
        mAdapter = new ListItemsAdapter(myListItems);

    private class ListItemsHolder extends RecyclerView.ViewHolder{
        public TextView mNameTextView;
        public ListItemsHolder(View itemView){
            mNameTextView = (TextView) itemView.findViewById(;

        public void bindData(ListItem s){
    private class ListItemsAdapter extends RecyclerView.Adapter{
        private ArrayList mListItems;
        public ListItemsAdapter(ArrayList ListItems){
            mListItems = ListItems;
        public ListItemsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(ListItemsActivity.this);
            View view = layoutInflater.inflate(R.layout.category_list_item_1,parent,false);
            return new ListItemsHolder(view);

        public void onBindViewHolder(ListItemsHolder holder, int position) {
            ListItem s = mListItems.get(position);
        public int getItemCount() {
            return mListItems.size();

To write data to the Firebase Database, we need an instance of DatabaseReference using
getInstance() method of FirebaseDatabase class.

We also need a reference to its child node “listItems”, to which we will add the list items. Next we declare an ArrayList of ListItems to store the Grocery List. We have added a reference to the RecyclerView which we have included in the layout of the activity.

We are using a Floating Action Button to add a new item to the list. For doing this we call our utility method createNewItem(). In this method we first create a new key using Firebase Database push().getKey() method.

We show an Alert Dialog to get the Grocery Item from the User.

Then we use the toMap() method described earlier to create a Map of the item. Then we add it to the Firebase Database using the updateChildren() we update the key with the List Item.

To retrieve data we add a ChildEventListener which has the following callback methods to decide action based upon the specific event.

onChildAdded() : It retrieve the lists of items as well as listen for additions to the list.
onChildChanged() : It actively Listens for changes made to the items in the list.
onChildRemoved() : It listens for items being removed from a list.
onChildMoved() : Listens for changes to the ordering of items in an ordered list.

The listener receives a DataSnapshot containing the data at the given location in the Firebase Database for the event. We get the data object using the getValue() on a snapshot. If no data exists it returns a null.

We are using the onChildAdded() callback to trigger fetchData() method, which gets the ListItem object, adds it to the ListItems ArrayList and calls the updateUI() method to reflect the changes.

In the updateUI() method we are creating a new ListItemAdapter and then setting it to the RecyclerView.

We have also provided a Menu Options to delete all the current items present in the list using the deleteAllListItems() where we are using Firebase Database removeValue() method on the “listItem” node.

Open the layout file activity_list_items.xml and add the following code.


We are using Android CoordinatorLayout with a RecyclerView and a FloatingActionButton for showing the list and adding the new items respectively.

Copy the following java files by downloading the code. These are required to authorize the user using Firebase Authentication .

  1. : The Login Activity for Firebase Authentication Tutorial
  2. : The Signup Activity for Firebase Authentication Tutorial
  3. : Java Class for adding the Line Divider in the RecyclerView(Refer to Android RecyclerView Tutorial to know more.)

Similarly Add the corresponding layout files and resources.

  1. activity_login.xml
  2. activity_signup.xml
  3. category_list_item_1.xml
  4. dialog_get_listItem.xml

Next Add these Activities to the AndroidManifest.xml. After adding these entries it should look as follows.


That’s all folks, run your app in the emulator or an actual device. Login to your app by signing up as firebase user, Now login again using the email and password you provided earlier and add a few Grocery Items. While adding, verfiy it gets reflected in the Firebase console. Later delete all the items using the menu option and see all the items gets deleted in the Firebase console also.

What’s Next ??

We hope you liked our Firebase Database example tutorial. You can also take a look at our Firebase Cloud Messaging Tutorial to add notifications capability to your android app. Please leave comments in the comment section below in case of any doubts.

Soon We will be covering articles on how to add Facebook and Google Sign-In using Firebase and how to integrate Firebase analytics to your app to get useful insights about the user base. Interested developers can explore more about firebase hosting and firebase security.

Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

To download the full code for the Firebase Database , Click on the Download Now link below.

The post Firebase Database Tutorial appeared first on Android Tutorial Point.

This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

Firebase Database Tutorial


Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription