Open In App

How to Save Data to the Firebase Realtime Database in Android?

Last Updated : 10 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Firebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simple app in which we will be adding our Data to Firebase Realtime Database. Note that we are going to implement this project using the Java language. 

What is Firebase Realtime Database? 

Firebase Realtime Database is a NoSQL cloud database that is used to store and sync the data. The data from the database can be synced at a time across all the clients such as android, web as well as IOS. The data in the database is stored in the JSON format and it updates in real-time with every connected client.  

What are the Advantages of using the Firebase Realtime Database? 

  • The main advantage of using the Firebase Realtime database is that the data is updated in a real-time manner and you don’t have to make any requests for the data updates or changes. The database uses data synchronization every time when data changes and these changes will reflect the connected user within milliseconds.
  • While using Firebase Realtime Database your apps remain responsive even if the device loses its connectivity to the database. Once the user has established the connection he will receive the changes made in the data from the database.
  • The data stored in the Firebase database can be easily accessible through the web portal of Firebase. You can manage your database from PC as well as mobile devices. You can manage the rules of the database which gives permissions to read and write operations to the database.

What We are Going to Build in This Article?

In this article, we are going to build a simple application in which we will be getting the data from the users with the help of some TextFields and store that data in the Firebase Realtime Database. Note that we are using Firebase Realtime Database and the app is written using JAVA language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Connect your app to Firebase

After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.

Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. 

After connecting your app to Firebase you will get to see the below screen. 

After that verify that dependency for Firebase Realtime database has been added to our Gradle file. Now navigate to the app > Gradle Scripts and inside that file check whether the below dependency is added or not. If the below dependency is not added in your build.gradle file. Add the below dependency in the dependencies section.

implementation ‘com.google.firebase:firebase-database:19.6.0’

After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about Adding Firebase to Android App. 

Step 3: Working with AndroidManifest.xml file

For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and inside that file add the below permissions to it. 

XML




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


Step 4: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--EditText for adding employee name-->
    <EditText
        android:id="@+id/idEdtEmployeeName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:hint="Enter Employee Name"
        android:importantForAutofill="no"
        android:inputType="textPersonName" />
 
    <!--EditText for adding employee phone-->
    <EditText
        android:id="@+id/idEdtEmployeePhoneNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtEmployeeName"
        android:layout_margin="10dp"
        android:hint="Enter employee phone number"
        android:importantForAutofill="no"
        android:inputType="phone" />
 
    <!--EditText for adding employee address-->
    <EditText
        android:id="@+id/idEdtEmployeeAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtEmployeePhoneNumber"
        android:layout_margin="10dp"
        android:hint="Enter employee address"
        android:inputType="textPostalAddress" />
 
    <!--Button for adding data to Firebase-->
    <Button
        android:id="@+id/idBtnSendData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtEmployeeAddress"
        android:layout_margin="10dp"
        android:text="Add employee details"
        android:textAllCaps="false" />
 
</RelativeLayout>


Step 5: Create a new Java class for storing our data

For sending multiple data to the Firebase Realtime database we have to create an Object class and send that whole object class to Firebase. For creating an object class navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java Class > Give a name to your class. In my case, it is EmployeeInfo, and add below code to it. 

Java




public class EmployeeInfo {
     
    // string variable for
    // storing employee name.
    private String employeeName;
     
    // string variable for storing
    // employee contact number
    private String employeeContactNumber;
     
    // string variable for storing
    // employee address.
    private String employeeAddress;
 
    // an empty constructor is
    // required when using
    // Firebase Realtime Database.
    public EmployeeInfo() {
 
    }
 
    // created getter and setter methods
    // for all our variables.
    public String getEmployeeName() {
        return employeeName;
    }
 
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
 
    public String getEmployeeContactNumber() {
        return employeeContactNumber;
    }
 
    public void setEmployeeContactNumber(String employeeContactNumber) {
        this.employeeContactNumber = employeeContactNumber;
    }
 
    public String getEmployeeAddress() {
        return employeeAddress;
    }
 
    public void setEmployeeAddress(String employeeAddress) {
        this.employeeAddress = employeeAddress;
    }
}


Step 6: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
 
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 AppCompatActivity {
 
    // creating variables for
    // EditText and buttons.
    private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;
    private Button sendDatabtn;
     
    // creating a variable for our
    // Firebase Database.
    FirebaseDatabase firebaseDatabase;
     
    // creating a variable for our Database
    // Reference for Firebase.
    DatabaseReference databaseReference;
     
    // creating a variable for
    // our object class
    EmployeeInfo employeeInfo;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        // initializing our edittext and button
        employeeNameEdt = findViewById(R.id.idEdtEmployeeName);
        employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber);
        employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress);
         
        // below line is used to get the
        // instance of our FIrebase database.
        firebaseDatabase = FirebaseDatabase.getInstance();
         
        // below line is used to get reference for our database.
        databaseReference = firebaseDatabase.getReference("EmployeeInfo");
         
        // initializing our object
        // class variable.
        employeeInfo = new EmployeeInfo();
 
        sendDatabtn = findViewById(R.id.idBtnSendData);
         
        // adding on click listener for our button.
        sendDatabtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
                // getting text from our edittext fields.
                String name = employeeNameEdt.getText().toString();
                String phone = employeePhoneEdt.getText().toString();
                String address = employeeAddressEdt.getText().toString();
                 
                // below line is for checking whether the
                // edittext fields are empty or not.
                if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) && TextUtils.isEmpty(address)) {
                    // if the text fields are empty
                    // then show the below message.
                    Toast.makeText(MainActivity.this, "Please add some data.", Toast.LENGTH_SHORT).show();
                } else {
                    // else call the method to add
                    // data to our database.
                    addDatatoFirebase(name, phone, address);
                }
            }
        });
    }
 
    private void addDatatoFirebase(String name, String phone, String address) {
        // below 3 lines of code is used to set
        // data in our object class.
        employeeInfo.setEmployeeName(name);
        employeeInfo.setEmployeeContactNumber(phone);
        employeeInfo.setEmployeeAddress(address);
         
        // we are use add value event listener method
        // which is called with database reference.
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                // inside the method of on Data change we are setting
                // our object class to our database reference.
                // data base reference will sends data to firebase.
                databaseReference.setValue(employeeInfo);
                 
                // after adding this data we are showing toast message.
                Toast.makeText(MainActivity.this, "data added", Toast.LENGTH_SHORT).show();
            }
 
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // if the data is not added or it is cancelled then
                // we are displaying a failure toast message.
                Toast.makeText(MainActivity.this, "Fail to add data " + error, Toast.LENGTH_SHORT).show();
            }
        });
    }
}


After adding this code go to this link for Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. 

After clicking on this screen you will get to see the below screen with your all project inside that select your project. 

Inside that screen click n Realtime Database in the left window. 

After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen. 

Inside this screen click on the Rules tab you will get to see the above screen and change the rules to true as shown in the screenshot. The rules are changed to true because we are not providing authentication inside our app and we have to write data to our database. That’s why we are specifying it to true. After changing your rules click on the publish rules button. Click on that option and your rules will be published. Now come back to the Data tab of your database.

Output:

Below is the video for our app for adding data to the Firebase Realtime Database. 

Run the app and make sure to connect your device to the internet. After that add some data in your text fields and click on the Insert data button. The data will be added to our Firebase Database. Below is the screenshot we will get to see after adding data to Firebase Database from the app.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads