Skip to content

Firebase Introduction

Firebase is a platform containing various Backend As a Service features. For example there is Firebase Realtime Database which is a database backend as a service. This means it provides realtime database features as a service, both paid and premium.

However more generally Firebase can be classified as a Mobile Backend As A service (MBaaS), or "backend as a service" (BaaS). This means it not provides mobile and web developers several services to include into their applications. This leads them to create much more powerful apps.

Generall BAAS platforms provide cloud storage capabilities as well as APIs that expose various functions, not just CRUD. For example here are some of the features generally provided by these platforms:

User Management and Authentication. Push Notifications. Analytics. Social Services integration. Custom development using APIs and SDK. Realtime databases.

Firebase Realtime Databse

Android Firebase Realtime Database Examples.

Firebase Realtime database is a database backend as a service Cloud hosted solution that gives us the platform to build rich apps.

Normally we are used to making HTTP requests to read or write data against our servers.But not in Firebase.It uses synchronization technology that allows it to be realtime,but still performant.

Main points

  • Its realtime : Therefore synchronizes data across all devices be it Mobile devices,PCs etc.Whenever there is a data change,events are fired and all connected devices get the updates.
  • Platfrom Independent – Being cloud hosted,any platform that can access internet can take advantage of its features.Be it from a PC,mobile device or web browser,or other servers.
  • Easy Access Control - Security-wise,there is Firebase Realtime database Security Rules.This is expressioned based rules that get called whenever data is to be persisted or read from our database.This ensures that clearly,you can control your data access using simple expressions,that of course get executed on the server side.
  • It’s a NoSQL solution and is heavily optimized for performance.
  • Has Offline capability : Firebase caches data on disk.These data can be accessed even when offline.Normally we are used to write so much code not only to make network operations,but also to oversee good user design guidelines that allows performant apps.The classic way is using threading classes like AsyncTask or Serives like IntentService to poll data so that our User Interface remains responsive.Because firebase persists data on the disk automatically,we don’t have to use the likes of IntentService to poll updates.
  • Its User Friendly.

Here is the new official firebase site.

Firebase vs SQLite Comparison.

Firebase Features

Some of the firebase features include :

(a). Analytics Solution

Gives you insights about your users,their behaviours as well as ad performance

  • Analytics .

(b). Developments Solution

Helps you build better applications.

  • Authentication - provide seamless user authentication within your apps.
  • Cloud Messaging - messaging across applications.
  • Realtime Database - realtime data storage and synchronization.
  • Hosting - host web content like html,css,javascript etc
  • Data Storage - store files like images,video and audio.
  • Remote Configurations - save configuration files on cloud to enable changing them on the fly.
  • Test Lab - app testing.
  • Crash Reporting - track your crash reports.

(c). User Engagement

Helps in user engagement and acquisition.

  • App Indexing - your app available in search results.
  • Notifications - notify users.
  • Adwords - google ads for your app.
  • Dynamic Links - links users to right sections in your application.
  • Invites - sharing from your application.

(d). Monetization Helps in monetizing your app.

  • Admob - monetize your app.

How Firebase Realtime Database Works

Firebase is realtime.Yes realtime.This means it syncs data across all connected clients or devices,irrespective of the devices themselves.Mmmh!.Be it from a web browser,mobile device,personal computer etc.

During this time the devices remain responsive because of how firebase works.Normally whenever we are doing network operations,be it polling updates from a remote serverWe do so classically by making HTTP requests,either to read or write resources.This normally requires us to do so in background threads or services,making the process tricky and with so much boilerplate.

With firebase, these gets done automatically for us. But even better, it does persist data to disk. So no need to manually write caching and data polling algorithms to maintain fresh data, while keeping our user interface responsive. This is big for real. In fact, even while offline, user can keep adding data.

These gets persisted in the disk. The app remains 100% responsive. Because Realtime events continue being raised. The network comes back. Device connects. The Firebase realtime database jumps to action. It syncs the local data with remote data. Any changes are resolved amicably.

But hey, what about security.Mmh! Security. Well Firebase comes with Firebase Realtime Database Security rules. This is a language, an expression based language. It controls your data access. When data can be read or written .It also structures your data.

Complex access levels can be realized with help of Firebase Authentication. Realtime Database API cannot solve everything. Only operations that complete quick are done using this API.

IMPLEMENTATION

  • Via Gradle.You include the Firebase realtime database SDK .
  • Create a Realtime database reference that points to your remote data store.
  • Save data, listen for changes
  • Enable offline persistence
  • Use rules to implement security

WHICH DATA TYPES TO STORE

Sure,we can have talked about Firebase Realtime Database and its cool.But not all data types will be good practice to store in it.For instance binary data like images,videos,pdf files,audio etc won’t be good saving in Firebase Realtime Database.

Instead Firebase or Google if you like,provides a more suited option in Firebase Storage. Code files like Html, CSS and javascript files can be hosted with Firebase Hosting.Also assets like fonts,icons,graphics etc. Infact,there is alson Firebase Remote Config can store app configurations in key value pairs.This can be used by developers to change UI appearance without need for an update.

Creating A new Firebase App

All the above features are independent.To create an app taking advantage of any of them,first you need to use your Google account.You sign up then move to Google Console here.

Resources

Firebase Official Guides.

Firebase Official Site.

Firebase Official reference

Android Firebase - Hello World - Save Data

Hi guys.In this an example tutorial we cover how to configure firebase realtime database with android and write a simple example of saving data into firebase from an edittext.

What we do:

  • Create google firebase account.
  • Create firebase project and database.
  • Save data from our android edittext to firebase

1. Setup

(a). Create Basic Activity Project
  1. First create a new project in android studio. Go to File --> New Project.

3. Create Firebase and Download Configuration File

Head over to Firebase Console, create a Firebase App, Register your app id and download the google-services.json file. Add it to your app folder.

(b). Specify Maven repository URL

Head over to project level(project folder) build.gradle and

  1. Add Google services classpath as below
  2. Add maven repository url
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.1.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
(c). Add Firebase Dependencies

Add them in you app level(app folder) build.gradle, then

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:cardview-v7:23.3.0'

    compile 'com.google.firebase:firebase-core:11.8.0'
    compile 'com.google.firebase:firebase-database:11.8.0'
}
apply plugin: 'com.google.gms.google-services'

Make sure you apply plugin: 'com.google.gms.google-services' as above.

Java Classes

(a). Our Model Class : Spacecraft.java

This is our model class representing a single spacecraft object.

The spacecraft will name,propellant and description properties.

package com.tutorials.hp.firebasestarter.m_Model;

public class Spacecraft {

    String name,propellant,description;

    public Spacecraft() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPropellant() {
        return propellant;
    }

    public void setPropellant(String propellant) {
        this.propellant = propellant;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}
(b). Our FirebaseHelper class.

Where we write to Firebase database CRUD code. In this example we are saving data to Firebase. This class will receive a DatabaseReference as a parameter when instantiate.

package com.tutorials.hp.firebasestarter.m_FireBase;

import com.google.firebase.database.DatabaseException;
import com.google.firebase.database.DatabaseReference;
import com.tutorials.hp.firebasestarter.m_Model.Spacecraft;

public class FirebaseHelper {

    DatabaseReference db;
    Boolean saved=null;

    public FirebaseHelper(DatabaseReference db) {
        this.db = db;
    }

    //SAVE
    public Boolean save(Spacecraft spacecraft)
    {
        if(spacecraft==null)
        {
            saved=false;
        }else
        {
            try
            {
                db.child("Spacecrafts").setValue(spacecraft);
                saved=true;

            }catch (DatabaseException e)
            {
                e.printStackTrace();
                saved=false;
            }
        }

        return saved;

    }
}
(c) Our MainActivity

This class is our main activity and derives from appcompatactivity.

  • Our launcher activitivity
  • We show input dialog.
  • UI Stuff.
package com.tutorials.hp.firebasestarter;

import android.app.Dialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.tutorials.hp.firebasestarter.m_FireBase.FirebaseHelper;
import com.tutorials.hp.firebasestarter.m_Model.Spacecraft;

public class MainActivity extends AppCompatActivity {

   DatabaseReference db;
    FirebaseHelper helper;
    EditText nameEditTxt,propTxt,descTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //SET UP FIREBASE DB
        db= FirebaseDatabase.getInstance().getReference();
        helper=new FirebaseHelper(db);

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

    //DISPLAY INPUT DIALOG
    private void displayInputDialog()
    {
        Dialog d=new Dialog(this);
        d.setTitle("Save To Firebase");
        d.setContentView(R.layout.input_dialog);

        nameEditTxt= (EditText) d.findViewById(R.id.nameEditText);
        propTxt= (EditText) d.findViewById(R.id.propellantEditText);
        descTxt= (EditText) d.findViewById(R.id.descEditText);
        Button saveBtn= (Button) d.findViewById(R.id.saveBtn);

        //SAVE
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //GET DATA
                String name=nameEditTxt.getText().toString();
                String propellant=propTxt.getText().toString();
                String desc=descTxt.getText().toString();

                //SET DATA
                Spacecraft s=new Spacecraft();
                s.setName(name);
                s.setPropellant(propellant);
                s.setDescription(desc);

                //SAVE
                if(name != null && name.length()>0)
                {
                    if(helper.save(s))
                    {
                        nameEditTxt.setText("");
                        propTxt.setText("");
                        descTxt.setText("");

                    }
                }else
                {
                    Toast.makeText(MainActivity.this, "Name Must Not Be Empty", Toast.LENGTH_SHORT).show();
                }

            }
        });

        d.show();
    }

}

Our Layouts

(a). activity_main.xml

Our main activity layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout

    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_fitsSystemWindows="true"
    tools_context="com.tutorials.hp.firebasestarter.MainActivity">

    <android.support.design.widget.AppBarLayout
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android_id="@+id/toolbar"
            android_layout_width="match_parent"
            android_layout_height="?attr/actionBarSize"
            android_background="?attr/colorPrimary"
            app_popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android_id="@+id/fab"
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_layout_gravity="bottom|end"
        android_layout_margin="@dimen/fab_margin"
        android_src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
(c). content_main.xml

This layout will get included in the activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout

    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    app_layout_behavior="@string/appbar_scrolling_view_behavior"
    tools_context="com.tutorials.hp.firebasestarter.MainActivity"
    tools_showIn="@layout/activity_main">

    <TextView
        android_layout_width="wrap_content"
        android_layout_height="wrap_content"
        android_text="Hello World!" />
</RelativeLayout>
(c). InputDialog.xml

This is our input dialog. Will contain edittexts for inputing data to Firebase.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android_orientation="vertical" android_layout_width="match_parent"
    android_layout_height="match_parent">

    <LinearLayout
        android_layout_width="fill_parent"
        android_layout_height="match_parent"
        android_layout_marginTop="?attr/actionBarSize"
        android_orientation="vertical"
        android_paddingLeft="15dp"
        android_paddingRight="15dp"
        android_paddingTop="50dp">

        <android.support.design.widget.TextInputLayout
            android_id="@+id/nameLayout"
            android_layout_width="match_parent"
            android_layout_height="wrap_content">

            <EditText
                android_id="@+id/nameEditText"
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_singleLine="true"
                android_hint= "Name" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android_id="@+id/propLayout"
            android_layout_width="match_parent"
            android_layout_height="wrap_content">

            <EditText
                android_id="@+id/propellantEditText"
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_singleLine="true"
                android_hint= "Propellant" />

        <android.support.design.widget.TextInputLayout
            android_id="@+id/descLayout"
            android_layout_width="match_parent"
            android_layout_height="wrap_content">

            <EditText
                android_id="@+id/descEditText"
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_singleLine="true"
                android_hint= "Description" />
        </android.support.design.widget.TextInputLayout>

        </android.support.design.widget.TextInputLayout>

        <Button android_id="@+id/saveBtn"
            android_layout_width="fill_parent"
            android_layout_height="wrap_content"
            android_text="Save"
            android_clickable="true"
            android_background="@color/colorAccent"
            android_layout_marginTop="40dp"
            android_textColor="@android:color/white"/>

    </LinearLayout>

</LinearLayout>

More Resources

Resource Link
GitHub Browse Browse
GitHub Download Link Download