Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaHow to Create and Add Data to Firebase Firestore in Android?

How to Create and Add Data to Firebase Firestore in Android?

Firebase is a famous product of Google which is used by so many developers to add backend functionality for their website as well as apps. The Firebase will make your job really easier for backend database and handling the database. In this article, we will take a look at the implementation of Firebase Firestore in Android. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update, and Delete) operation with Firebase Firestore in Android. We are going to cover the following 4 articles in this series:

  1. How to Create and Add Data to Firebase Firestore in Android?
  2. How to Read Data from Firebase Firestore in Android?
  3. How to Update Data in Firebase Firestore in Android?
  4. How to Delete Data from Firebase Firestore in Android?

What is Firebase Firestore? 

Firebase Firestore is a cloud NoSQL database that is used to add, retrieve, and update data inside your application. Basically, it is a database that is used to store data inside your Firebase console. The data in the Firestore is stored in the form of documents, so it becomes easy to manage this data inside Firebase. 

What is the benefit of using Firestore over Firebase Realtime Database?   

Firestore is having a better query than that of Firebase Realtime Database. It is highly scalable and data can be managed properly inside Firebase Firestore. It becomes easy to access data on the server-side inside the Firebase Firestore database. Firebase Firestore is much easier in comparison to Firebase Realtime Database. You can check a more detailed guide on Firebase Realtime Database vs Firestore database

What we will be building in this article? 

In this article, we will be building a simple Android Application in which we will be collecting the data from users via some TextFields and we will send that data to our Firebase Cloud Firestore console and that data will get store in our Firebase database. 

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 Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option 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 Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. 

implementation ‘com.google.firebase:firebase-firestore:22.0.1’

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 How to add Firebase to Android App.  

Step 3: Working with the 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. Inside that file add the below permissions to it.  

XML




<!--Permissions for internet-->
<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"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--Edittext for getting course Name-->
    <EditText
        android:id="@+id/idEdtCourseName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="10dp"
        android:hint="Course Name"
        android:importantForAutofill="no"
        android:inputType="text" />
 
    <!--Edittext for getting course Duration-->
    <EditText
        android:id="@+id/idEdtCourseDuration"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="10dp"
        android:hint="Course Duration in min"
        android:importantForAutofill="no"
        android:inputType="time" />
 
    <!--Edittext for getting course Description-->
    <EditText
        android:id="@+id/idEdtCourseDescription"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="10dp"
        android:hint="Course Description"
        android:importantForAutofill="no"
        android:inputType="text" />
 
    <!--Button for adding your course to Firebase-->
    <Button
        android:id="@+id/idBtnSubmitCourse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Submit Course Details"
        android:textAllCaps="false" />
 
</LinearLayout>


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

For sending data to the Firebase Firestore 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. Here we named it Courses and add the below code to it.   

Java




public class Courses {
 
    // variables for storing our data.
    private String courseName, courseDescription, courseDuration;
 
    public Courses() {
        // empty constructor
        // required for Firebase.
    }
 
    // Constructor for all variables.
    public Courses(String courseName, String courseDescription, String courseDuration) {
        this.courseName = courseName;
        this.courseDescription = courseDescription;
        this.courseDuration = courseDuration;
    }
 
    // getter methods for all variables.
    public String getCourseName() {
        return courseName;
    }
 
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
 
    public String getCourseDescription() {
        return courseDescription;
    }
 
    // setter method for all variables.
    public void setCourseDescription(String courseDescription) {
        this.courseDescription = courseDescription;
    }
 
    public String getCourseDuration() {
        return courseDuration;
    }
 
    public void setCourseDuration(String courseDuration) {
        this.courseDuration = courseDuration;
    }
}


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.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
 
public class MainActivity extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
 
    // creating variable for button
    private Button submitCourseBtn;
 
    // creating a strings for storing
    // our values from edittext fields.
    private String courseName, courseDuration, courseDescription;
 
    // creating a variable
    // for firebasefirestore.
    private FirebaseFirestore db;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // getting our instance
        // from Firebase Firestore.
        db = FirebaseFirestore.getInstance();
 
        // initializing our edittext and buttons
        courseNameEdt = findViewById(R.id.idEdtCourseName);
        courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);
        courseDurationEdt = findViewById(R.id.idEdtCourseDuration);
        submitCourseBtn = findViewById(R.id.idBtnSubmitCourse);
 
        // adding on click listener for button
        submitCourseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                // getting data from edittext fields.
                courseName = courseNameEdt.getText().toString();
                courseDescription = courseDescriptionEdt.getText().toString();
                courseDuration = courseDurationEdt.getText().toString();
 
                // validating the text fields if empty or not.
                if (TextUtils.isEmpty(courseName)) {
                    courseNameEdt.setError("Please enter Course Name");
                } else if (TextUtils.isEmpty(courseDescription)) {
                    courseDescriptionEdt.setError("Please enter Course Description");
                } else if (TextUtils.isEmpty(courseDuration)) {
                    courseDurationEdt.setError("Please enter Course Duration");
                } else {
                    // calling method to add data to Firebase Firestore.
                    addDataToFirestore(courseName, courseDescription, courseDuration);
                }
            }
        });
    }
 
    private void addDataToFirestore(String courseName, String courseDescription, String courseDuration) {
 
        // creating a collection reference
        // for our Firebase Firestore database.
        CollectionReference dbCourses = db.collection("Courses");
 
        // adding our data to our courses object class.
        Courses courses = new Courses(courseName, courseDescription, courseDuration);
 
        // below method is use to add data to Firebase Firestore.
        dbCourses.add(courses).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                // after the data addition is successful
                // we are displaying a success toast message.
                Toast.makeText(MainActivity.this, "Your Course has been added to Firebase Firestore", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // this method is called when the data addition process is failed.
                // displaying a toast message when data addition is failed.
                Toast.makeText(MainActivity.this, "Fail to add course \n" + e, Toast.LENGTH_SHORT).show();
            }
        });
    }
}


After adding this code go to this link to open 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 Firebase Firestore Database in the left window.  

After clicking on the Create Database option you will get to see the below screen. 

Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen.  

Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on the submit button. You will get to see the data added inside the Firebase Console.  

Below is the output of the app.

Output:

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments