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 firebase.google.com 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 'com.google.gms:google-services:3.0.0'
    
  6. Next, open your app’s build.gradle from the and add the following at the end.
  7. build.gradle

    	apply plugin: 'com.google.gms.google-services'
    
  8. Also add the following dependencies in the dependencies section.
  9.     compile 'com.google.firebase:firebase-auth:9.0.2'
        compile 'com.google.firebase:firebase-core:9.0.2'
        compile 'com.google.firebase:firebase-database:9.0.2'
        compile 'com.android.support:recyclerview-v7:24.2.0'
    

Working with Firebase Database

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

ListItem.java

package com.androidtutorialpoint.firebasegrocerylistapp;

import com.google.firebase.database.Exclude;
import com.google.firebase.database.IgnoreExtraProperties;

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

@IgnoreExtraProperties
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;
    }

    @Override
    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;
    }

    @Exclude
    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 ListItemsActivity.java and then we will explain the complete functionality step by step.

ListItemsActivity.java

package com.androidtutorialpoint.firebasegrocerylistapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
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 com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

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;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_items);

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createNewListItem();
            }
        });

        mListItemRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG+"Added",dataSnapshot.getValue(ListItem.class).toString());
                fetchData(dataSnapshot);

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG+"Changed",dataSnapshot.getValue(ListItem.class).toString());
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Log.d(TAG+"Removed",dataSnapshot.getValue(ListItem.class).toString());
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG+"Moved",dataSnapshot.getValue(ListItem.class).toString());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG+"Cancelled",databaseError.toString());
            }
        });
    }

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

    @Override
    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();
        switch(id){
            case R.id.action_delete_all:
                deleteAllListItems();
                break;
            case R.id.action_logout:
                FirebaseAuth.getInstance().signOut();
                startActivity(new Intent(this, LoginActivity.class));
                break;
        }
        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);
        alertDialogBuilder.setView(getListItemView);

        final EditText userInput = (EditText) getListItemView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .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);
                        FirebaseDatabase.getInstance().getReference().updateChildren(childUpdates);

                    }
                }).create()
                .show();

    }

    public void deleteAllListItems(){
        FirebaseDatabase.getInstance().getReference().child("listItem").removeValue();
        myListItems.clear();
        mAdapter.notifyDataSetChanged();
        Toast.makeText(this,"Items Deleted Successfully",Toast.LENGTH_SHORT).show();
    }

    private void fetchData(DataSnapshot dataSnapshot) {
        ListItem listItem=dataSnapshot.getValue(ListItem.class);
        myListItems.add(listItem);
        updateUI();
    }

   private void updateUI(){
        mAdapter = new ListItemsAdapter(myListItems);
        mListItemsRecyclerView.setAdapter(mAdapter);
    }

    private class ListItemsHolder extends RecyclerView.ViewHolder{
        public TextView mNameTextView;
        public ListItemsHolder(View itemView){
            super(itemView);
            mNameTextView = (TextView) itemView.findViewById(R.id.textview_name);
        }

        public void bindData(ListItem s){
            mNameTextView.setText(s.getListItemText());
        }
    }
    private class ListItemsAdapter extends RecyclerView.Adapter{
        private ArrayList mListItems;
        public ListItemsAdapter(ArrayList ListItems){
            mListItems = ListItems;
        }
        @Override
        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);

        }
        @Override
        public void onBindViewHolder(ListItemsHolder holder, int position) {
            ListItem s = mListItems.get(position);
            holder.bindData(s);
        }
        @Override
        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.

activity_list_items.xml

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. LoginActivity.java : The Login Activity for Firebase Authentication Tutorial
  2. SignupActivity.java : The Signup Activity for Firebase Authentication Tutorial
  3. SimpleDividerItemDecoration.java : 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.

AndroidManifest.xml

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

×