Firebase Integration in Android Tutorial

Udemy Generic 728x90

Objective

In this tutorial, we will learn how to integrate Firebase with Android application and store and sync data to Firebase through a simple example.

 




 

Firebase provides backend services for managing apps. Firebase provides Json database to store and sync app data. Firebase provides an API that allows application data to be synchronized across clients and stored on Firebase cloud.

In this tutorial, we will learn how to integrate Firebase with an Android application and also learn how to store data to Firebase from Android application. To integrate Firebase, we need to create an account on Firebase.
 

Step 2

Create a New Project

Create a new Project in Android Studio, goto File ⇒ New ⇒ New Projects.
 

Step 3

Create Firebase App

To integrate Firebase with Android application, follow these steps:

  • Login to Firebase
  • We will create an application on Firebase. We will see a form on Dashboard of Firebase account. Fill App name and we need not to fill APP Url. It automatically fills up according to your App name. Click on Create New App button.

    create firebase app

 

Step 4

Add Supporting Library

To use Firebase’s features, we need to add supporting library of Firebase in Android project. So, open your build.gradle file and add supporting library of Firebase as dependency.

dependencies {
  ....
    compile 'com.firebase:firebase-client-android:2.5.1+'
  ....
}

 

Step 5

Add Packaging Options

If you are getting error at compile time about duplicate files. We need to add a packagingOptions directive to build.gradle file in android section.

android {
    ...
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}

 

Step 6

Add Internet Permissions

To store data to Firebase, Your Android App needs to request Internet permission. So, So we need to add Internet permission in AndroidManifest.xml file.

 <uses-permission android:name="android.permission.INTERNET" />

 

Step 7

Setup Firebase on Android

Firebase library must be initialized, before any Firebase app is created or used. To initialize Firebase library, add Firebase.setAndroidContext(this) in onCreate() method.

// Initialize firebase library with context
Firebase.setAndroidContext(this);

 

Step 8

Add Firebase Database Url

To read and write database, we need to call Firebase Constructor and pass database url of your Firebase. Use the following code:

/**
 * Call Firebase constructor and pass database url of firebase app.
 */
public void appReference(){
    // Replace numapp with your app name
    myFirebaseRef = new Firebase("https://numapp.firebaseio.com/");
}

 

Step 9

Create Data to Firebase

We can save data by using setValue() method. We can store Boolean, Long, Double, Map<String, Object> or List data types to Firebase. In this example, we will save a Json object to Firebase. We need to create a child named as “user” by calling child() method. Create a HashMap<String, String> object to add Name and Birthday value. Pass this object into Another HashMap and also pass it in setValue() method.

/**
 * Create Hashmap object and put birthday and full name.
 * Add this hash map in &quot;post&quot; key value pair
 * store data on Firebase, by using setValue() method.
 */
 public void createData(){

    Firebase usersRef  = myFirebaseRef.child(&quot;users&quot;);

    Map&lt;String, String&gt; userMap = new HashMap&lt;String, String&gt;();
    userMap.put(&quot;birthYear&quot;, &quot;2012&quot;);
    userMap.put(&quot;Name&quot;, &quot;ALok&quot;);

    Map&lt;String, Map&lt;String, String&gt;&gt; users = new HashMap&lt;String, Map&lt;String, String&gt;&gt;();
    users.put(&quot;Post&quot;, userMap);
    usersRef.setValue(users);
 }

 

Above code will save data in the following format:

{
  &quot;users&quot;: {
    &quot;Post&quot;: {
      &quot;birthYear&quot;: &quot;2012&quot;,
      &quot;Name&quot;: &quot;ALok&quot;
    }
  }
}

 

Step 10

Read Store Data

We can read stored data from Firebase database by adding Listener and handling the result event. We need to call addValueEventListener() method of child value of Firebase database.

/**
 *  Adding Listener and handling the result by call addValueEventListener() method 
 *  for specific value of Firebase database
 */
 public void childListener(){

    myFirebaseRef.child(&quot;users&quot;).addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot snapshot) {
            Log.e(&quot;result&quot;, snapshot.getValue()+&quot;&quot;);
           
        }

        @Override
        public void onCancelled(FirebaseError error) {

             Log.e(&quot;The read failed: &quot;, error.getMessage());
         }

    });
}

Print result in onDataChange() method:

{
  &quot;users&quot;: {
    &quot;Posts&quot;: {
      &quot;birthYear&quot;: &quot;2012&quot;,
      &quot;Name&quot;: &quot;ALok&quot;
    }
  }
}

 

Step 11

Save Multiple Json data

We can add multiple object into a single child. We will create a child by calling child() method of Firebase class and create separate multiple object by using HashMap. Add that object into a new HashMap and pass it into setValue() method.

/**
 * Created a &quot;MultiUser&quot; child.
 * Created separate multiple object.
 * Adding all object into a new HaspMap and pass it into setValue() method
 */
 public void multiChild(){

     Firebase usersRef  = myFirebaseRef.child(&quot;MultiUser&quot;);

     Map&lt;String, Object&gt; name1 = new HashMap&lt;String, Object&gt;();
     name1.put(&quot;name&quot;, &quot;Alan&quot;);

     Map&lt;String, Object&gt; name2 = new HashMap&lt;String, Object&gt;();
     name2.put(&quot;name&quot;, &quot;Grace&quot;);

     Map&lt;String, Object&gt; nickname = new HashMap&lt;String, Object&gt;();

     nickname.put(&quot;alan&quot;, name1);
     nickname.put(&quot;grace&quot;, name2);

     usersRef.setValue(nickname);
 }

 

Above code will save data to Firebase in the following format:

{
  &quot;MultiUser&quot;: {
    &quot;alan&quot;: {
      &quot;name&quot;: &quot;Alan&quot;
    },
    &quot;grace&quot;: {
      &quot;name&quot;: &quot;Grace&quot;
    }
  }
}

 

Step 12

Updating Specific Fields

If we want to update to specific children without overwriting other child, we need to use updateChildren() method instead of setValue() method. In this example, we are going to update name of “alan” object of MultiUser child

/**
 * Update MultiUser child node data
 */
public void updateData(){

    Firebase usersRef = myFirebaseRef.child(&quot;MultiUser&quot;);

    Firebase alanRef = usersRef.child(&quot;alan&quot;);
    Map&lt;String, Object&gt; nickname = new HashMap&lt;String, Object&gt;();
    nickname.put(&quot;name&quot;, &quot;Alan The Machine&quot;);
    alanRef.updateChildren(nickname);
}

 

Step 13

Final Code

Here is the final code:

public class MainActivity extends AppCompatActivity {

    private Firebase myFirebaseRef;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize Firebase library with context
        Firebase.setAndroidContext(this);
        
        // Calling appReference() method
        appReference();
        
        // Calling createData() method
        createData();
        
        // Calling multiChild() method
        multiChild();

        // Update data by calling updateData()
        updateData();

    }

    /**
     * Call Firebase constructor and pass database url of firebase app.
     */
    public void appReference(){
        // Replace numapp with your app name
        myFirebaseRef = new Firebase(&quot;https://numapp.firebaseio.com/&quot;);
    }

    /**
     * Create Hashmap object and put birthday and full name.
     * Add this hash map in &quot;post&quot; key value pair
     * store data on Firebase, by using setValue() method.
     */
    public void createData(){

        Firebase usersRef  = myFirebaseRef.child(&quot;users&quot;);

        Map&lt;String, String&gt; userMap = new HashMap&lt;String, String&gt;();
        userMap.put(&quot;birthYear&quot;, &quot;2012&quot;);
        userMap.put(&quot;Name&quot;, &quot;ALok&quot;);

        Map&lt;String, Map&lt;String, String&gt;&gt; users = new HashMap&lt;String, Map&lt;String, String&gt;&gt;();
        users.put(&quot;Post&quot;, userMap);
        usersRef.setValue(users);

        childListener();
    }

    /**
     *  Adding Listener and handling the result by call addValueEventListener() method
     *  for specific value of Firebase database
     */
    public void childListener(){

        myFirebaseRef.child(&quot;users&quot;).addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot snapshot) {
                Log.e(&quot;result&quot;, snapshot.getValue() + &quot;.....&quot; + snapshot.getKey());
                System.out.println(snapshot.getValue());
            }

            @Override
            public void onCancelled(FirebaseError error) {

                Log.e(&quot;The read failed: &quot;, error.getMessage());
            }

        });
    }

    /**
     * Created a &quot;MultiUser&quot; child.
     * Created separate multi[ple object.
     * Adding all object into a new HaspMap and pass it into setValue() method
     */
    public void multiChild(){

        Firebase usersRef  = myFirebaseRef.child(&quot;MultiUser&quot;);

        Map&lt;String, Object&gt; name1 = new HashMap&lt;String, Object&gt;();
        name1.put(&quot;name&quot;, &quot;Alan&quot;);

        Map&lt;String, Object&gt; name2 = new HashMap&lt;String, Object&gt;();
        name2.put(&quot;name&quot;, &quot;Grace&quot;);

        Map&lt;String, Object&gt; nickname = new HashMap&lt;String, Object&gt;();

        nickname.put(&quot;alan&quot;, name1);
        nickname.put(&quot;grace&quot;, name2);

        usersRef.setValue(nickname);
    }

    /**
     * Update MultiUser child node data
     */
    public void updateData(){

        Firebase usersRef = myFirebaseRef.child(&quot;MultiUser&quot;);

        Firebase alanRef = usersRef.child(&quot;alan&quot;);
        Map&lt;String, Object&gt; nickname = new HashMap&lt;String, Object&gt;();
        nickname.put(&quot;name&quot;, &quot;Alan The Machine&quot;);
        alanRef.updateChildren(nickname);
    }
}

 

firebase database




Udemy Generic 728x90

Spread the word. Share this post!

  • After updateData(), I am trying to clean the edittext in my layout but I am not able to do it. I have been debbuging the code and after doing updateChildren(nickname) this function I am not able to clean my edittexts. Do you know what is happening?

  • Vishal Patoliya

    Very very usefull
    Really thakfull too those persion who contribute.!!!!!!!!!!