Open In App

How to Delete Data from Firebase Firestore in Android?

Last Updated : 22 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In the previous article, we have seen on How to Add Data, Read Data, and Update data in Firebase Firestore in Android. Now we will see How to Delete this added data inside our Firebase Firestore. So we will move towards the implementation of this deleting data in Android Firebase.  

What we are going to build in this article?  

We will be adding a simple button inside our update screen where we were updating our data and inside that screen, we will be adding a new button for deleting the course. After deleting, that course will be deleted from our database. 

Step by Step Implementation

Step 1: Creating a new button for deleting the data inside the activity_update_course.xml file

As we have created a new Update Course Activity in the previous article. So we will simply add a new button to it. Add the following code snippet to the activity_update_course.xml file. 

XML




<!--Button for deleting our course-->
<Button
  android:id="@+id/idBtnDeleteCourse"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:layout_margin="10dp"
  android:layout_weight="1"
  android:text="Delete Course"
  android:textAllCaps="false" />


 
Below is the updated code for the activity_update_course.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=".UpdateCourse">
 
    <!--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" />
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="2">
 
        <!--Button for updating your course to Firebase-->
        <Button
            android:id="@+id/idBtnUpdateCourse"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:text="Update Course"
            android:textAllCaps="false" />
 
        <!--Button for deleting our course-->
        <Button
            android:id="@+id/idBtnDeleteCourse"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:text="Delete Course"
            android:textAllCaps="false" />
 
    </LinearLayout>
 
</LinearLayout>


Step 2: Now we have to initialize this button in the UpdateCourses.java file and add onClickListener to it 

Go to the UpdateCourses.java file and add the following code snippet. 

Java




// adding on click listener for delete button
deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling method to delete the course.
                deleteCourse(courses);
        }
  });
 
private void deleteCourse(Courses courses) {
        // below line is for getting the collection
        // where we are storing our courses.
        db.collection("Courses").
                // after that we are getting the document
                // which we have to delete.
                document(courses.getId()).
                 
                // after passing the document id we are calling
                // delete method to delete this document.
                delete().
                        // after deleting call on complete listener
                        // method to delete this data.
                        addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        // inside on complete method we are checking
                        // if the task is success or not.
                        if (task.isSuccessful()) {
                            // this method is called when the task is success
                            // after deleting we are starting our MainActivity.
                            Toast.makeText(UpdateCourse.this, "Course has been deleted from Database.", Toast.LENGTH_SHORT).show();
                            Intent i = new Intent(UpdateCourse.this, MainActivity.class);
                            startActivity(i);
                        } else {
                            // if the delete operation is failed
                            // we are displaying a toast message.
                            Toast.makeText(UpdateCourse.this, "Fail to delete the course. ", Toast.LENGTH_SHORT).show();
                        }
                 }
         });
 }


 
Below is the updated code for the UpdateCourses.java file.  

Java




import android.content.Intent;
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.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
 
public class UpdateCourse extends AppCompatActivity {
 
    // creating variables for our edit text
    private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;
 
    // 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_update_course);
        Courses courses = (Courses) getIntent().getSerializableExtra("course");
 
        // 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);
 
        // creating variable for button
        Button updateCOurseBtn = findViewById(R.id.idBtnUpdateCourse);
        Button deleteBtn = findViewById(R.id.idBtnDeleteCourse);
 
        courseNameEdt.setText(courses.getCourseName());
        courseDescriptionEdt.setText(courses.getCourseDescription());
        courseDurationEdt.setText(courses.getCourseDuration());
 
        // adding on click listener for delete button
        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling method to delete the course.
                deleteCourse(courses);
            }
        });
 
        updateCOurseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                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 a method to update our course.
                    // we are passing our object class, course name,
                    // course description and course duration from our edittext field.
                    updateCourses(courses, courseName, courseDescription, courseDuration);
                }
            }
        });
    }
 
    private void deleteCourse(Courses courses) {
        // below line is for getting the collection
        // where we are storing our courses.
        db.collection("Courses").
                // after that we are getting the document
                // which we have to delete.
                document(courses.getId()).
 
                // after passing the document id we are calling
                // delete method to delete this document.
                delete().
                        // after deleting call on complete listener
                        // method to delete this data.
                        addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        // inside on complete method we are checking
                        // if the task is success or not.
                        if (task.isSuccessful()) {
                            // this method is called when the task is success
                            // after deleting we are starting our MainActivity.
                            Toast.makeText(UpdateCourse.this, "Course has been deleted from Database.", Toast.LENGTH_SHORT).show();
                            Intent i = new Intent(UpdateCourse.this, MainActivity.class);
                            startActivity(i);
                        } else {
                            // if the delete operation is failed
                            // we are displaying a toast message.
                            Toast.makeText(UpdateCourse.this, "Fail to delete the course. ", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
 
    private void updateCourses(Courses courses, String courseName, String courseDescription, String courseDuration) {
        // inside this method we are passing our updated values
        // inside our object class and later on we
        // will pass our whole object to firebase Firestore.
        Courses updatedCourse = new Courses(courseName, courseDescription, courseDuration);
 
        // after passing data to object class we are
        // sending it to firebase with specific document id.
        // below line is use to get the collection of our Firebase Firestore.
        db.collection("Courses").
                // below line is use toset the id of
                // document where we have to perform
                // update operation.
                document(courses.getId()).
 
                // after setting our document id we are
                // passing our whole object class to it.
                set(updatedCourse).
 
                // after passing our object class we are
                // calling a method for on success listener.
                addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        // on successful completion of this process
                        // we are displaying the toast message.
                        Toast.makeText(UpdateCourse.this, "Course has been updated..", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
            // inside on failure method we are
            // displaying a failure message.
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(UpdateCourse.this, "Fail to update the data..", Toast.LENGTH_SHORT).show();
            }
        });
    }
}


Output:

The Final Project File Structure

Below is the file structure for Java files: 

Below is the file structure for XML files:

 



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

Similar Reads