📌  相关文章
📜  如何从Android中的Firebase Firestore删除数据?

📅  最后修改于: 2021-05-10 13:35:20             🧑  作者: Mango

在上一篇文章中,我们了解了如何 在Android的Firebase Firestore中添加数据,读取数据和更新数据。现在,我们将看到如何在Firebase Firestore中删除此添加的数据。因此,我们将着手在Android Firebase中实现此删除数据。

我们将在本文中构建什么?

我们将在要更新数据的更新屏幕内添加一个简单的按钮,并在该屏幕内添加用于删除课程的新按钮。删除后,该课程将从我们的数据库中删除。

分步实施

步骤1:创建一个新按钮以删除activity_update_course.xml文件中的数据

由于我们在上一篇文章中创建了一个新的更新课程活动。因此,我们只需向其添加一个新按钮。将以下代码片段添加到activity_update_course.xml文件中。

XML


XML


  
    
    
  
    
    
  
    
    
  
    
  
        
        


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() {
                    @Override
                    public void onComplete(@NonNull Task 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 Databse.", 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();
                        }
                 }
         });
 }


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() {
                    @Override
                    public void onComplete(@NonNull Task 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 Databse.", 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() {
                    @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();
            }
        });
    }
}


以下是activity_update_course.xml文件的更新代码。

XML格式



  
    
    
  
    
    
  
    
    
  
    
  
        
        

步骤2:现在我们必须在UpdateCourses中初始化此按钮。 Java文件并将onClickListner添加到它

转到UpdateCourses。 Java文件,并添加以下代码段。

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() {
                    @Override
                    public void onComplete(@NonNull Task 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 Databse.", 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();
                        }
                 }
         });
 }

下面是UpdateCourses的更新代码。 Java文件。

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() {
                    @Override
                    public void onComplete(@NonNull Task 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 Databse.", 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() {
                    @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();
            }
        });
    }
}

输出:

最终项目文件结构

以下是Java文件的文件结构:

以下是XML文件的文件结构:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!