How to add Android Firebase Database to Android Project

Firebase real-time database is a cloud database from Google. It has many features that make it easier to create a prototype or a new application with remote data storage.

We will not go into detail description of what Firebase database is or what it is used for. Rather we will explore with different code examples on how to achieve some given task using Firebase database.

If you want to read about Firebase database, there are lot of information in the official guide here.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Ways to add Firebase database to android project.

First Method

You can manually add Firebase database to your project by

  1. Go to Firebase Database console and create a new Firebase project
  2. Enable Firebase Real-Time Database
  3. Add Firebase configuration file in android project app directory
  4. Add the Google services plugin classpath in android project level build.gradle file – classpath 'com.google.gms:google-services:4.2.0'
  5. Add Firebase Core and Firebase Database libraries in the dependency section of the build.gradle
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-database:17.0.0'

Second Method

You can add Firebase database if you are using Android Studio. Android Studio has a seamless integration of Firebase services with simple clicks.

To add Firebase database in your project using Android Studio

  1. Click on Tool Menu
  2. Go to Firebase submenu
  3. In the open window dialog, select create Firebase project
  4. Once it is done, you will see a green tick that indicates Firebase has been abled
  5. Then add Firebase database

When everything is done, check the project and you will see that Android Studio has add all the code and resources Firebase database requires

Test the project

Now that we have added Firebase real-time database, let us test if it is working.

We will create a simple code example that accepts input and when we click on a button, the input will be stored in the Firebase database.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="15dp"
    android:background="#CACACA">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/titleinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="90dp">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/title"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/bodyinput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/titleinput">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/body"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/body"
            android:inputType="textNoSuggestions"
            android:maxLines="1"
            android:singleLine="true" />
    </com.google.android.material.textfield.TextInputLayout>


    <Button
        android:id="@+id/submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_below="@id/bodyinput"
        android:textColor="#ffffff"
        android:text="Submit"/>

</RelativeLayout>

MainActivity.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class FirebaseActivity1 extends AppCompatActivity {
    private TextInputEditText title;
    private TextInputEditText body;
    private DatabaseReference mDatabase;
    private Button submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firebase1);
        title = (TextInputEditText)findViewById(R.id.title);
        body = (TextInputEditText)findViewById(R.id.body);
        submit = (Button)findViewById(R.id.submit);
        mDatabase = FirebaseDatabase.getInstance().getReference().child("AndroidView");

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String enteredtitle = title.getText().toString();
                String enteredbody = body.getText().toString();
                saveData(enteredtitle, enteredbody);
            }
        });


    }
    private void saveData(String strTitle, String strBody){
        DatabaseReference newEntry = mDatabase.push();
        newEntry.child("title").setValue(strTitle);
        newEntry.child("content").setValue(strBody)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(FirebaseActivity1.this,"Data Inserted",Toast.LENGTH_LONG).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(FirebaseActivity1.this,e.getMessage(),Toast.LENGTH_LONG).show();
            }
        });
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment