Srikanth Technologies

Using Firebase from Android Application

In this blog, I show how to get started with Firebase database and use it from an Android application.

What is Firebase?

Firebase is a realtime database provided by Google. It stores data in JSON format and syncs data between applications running on different devices in realtime using cloud-hosted noSQL database. Data is synced in milliseconds across connected devices.

It is possible to access Firebase data from IOS, Android and JavaScript applications.

So, once you store your data in Firebase, you can update and retrieve data across devices that use IOS, Android and Desktops that run JavaScript.

Getting started with Firebase

In order to use Firebase, you need to log into your google account and take the following steps: Now we have a Firebase database with a node called course with value Android Programming. Let us see how to access it from an Android Application.

Creating Android Application

We create a simple Android application to retrieve and update data of course node in Firebase database.

Connecting Android Application To Firebase Project

It is time to connect our application to Firebase database. Here are the steps to connect Android Application to Firebase database.

Working with Android Application

It is time to create an Activity in Android Application and connect to Firebase database to update and retrieve data from course node.

Add the following components to your Android application:

MainActivity.java

package com.srikanthtechnologies.firebaseapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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 com.google.firebase.database.ValueEventListener;

public class MainActivity extends Activity {

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference rootRef = database.getReference();
    DatabaseReference courseRef = rootRef.child("course");
    EditText editCourseName;
    TextView textCourseName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editCourseName = (EditText) findViewById(R.id.editCourseName);
        textCourseName = (TextView) findViewById(R.id.textCourseName);

        // handle value event for course node
        courseRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                    textCourseName.setText(dataSnapshot.getValue().toString());
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    public void updateCourse(View v) {
        // Write a value to course node
        courseRef.setValue(editCourseName.getText().toString());
        Toast.makeText(this,"Updated Course", Toast.LENGTH_LONG).show();
    }

}

Activity_Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textCourseName"
        android:gravity="center"
        android:textColor="#ff0000"
        android:textAppearance="?android:textAppearanceMedium"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

   <EditText
        android:id="@+id/editCourseName"
        android:hint="Course Name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:onClick="updateCourse"
        android:text="Update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
            
</LinearLayout>
    

AndroidManifest.xml

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.srikanthtechnologies.firebaseapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>
        

Updated Gradle Build Files - app/build.gradle

When we wanted to use Firebase from our application, we added some entries to gradle build files through Tools->Firebase. These entries add required library and google service plugin as shown below:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.srikanthtechnologies.firebaseapp"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.firebase:firebase-database:10.0.1'
    testCompile 'junit:junit:4.12'
}


apply plugin: 'com.google.gms.google-services'

Testing

It is time to test Android application to see whether we can retrieve and update Firebase data.

Build Android Application using Build -> Build APK.

Run Android Application either in Emulator or Device. In the beginning, MainActivity must show current value of course node from Firebase database as shown in the following screen:

Enter new course name (Angular 2 Programming) in EditText and click on Update button to change value in Firebase database.

As Firebase database changes, it notifies our application about change by calling onDateChange method. We update our TextView with new value. Remember, no matter how the value of course is changed in Firebase, our application is notified with onDataChange event to enable our application to take a Snapshot of data.

Here are some links that provide you relevant details:

Add Firebase to your Android Project
Firebase Documentation