📜  如何在Android中创建数据并将数据添加到Firebase Firestore?

📅  最后修改于: 2021-05-09 18:37:42             🧑  作者: Mango

Firebase是Google的著名产品,许多开发人员都在使用Firebase为其网站和应用添加后端功能。 Firebase将使后端数据库和数据库处理的工作变得更加轻松。在本文中,我们将介绍AndroidFirebase Firestore的实现。这是系列文章,共4篇,我们将在Android中使用Firebase Firestore执行基本的CRUD(创建,读取,更新和删除)操作。我们将在本系列中涵盖以下4篇文章:

  1. 如何在Android中创建数据并将数据添加到Firebase Firestore?
  2. 如何从Android中的Firebase Firestore读取数据?
  3. 如何在Android的Firebase Firestore中更新数据?
  4. 如何从Android中的Firebase Firestore删除数据?

什么是Firebase Firestore?

Firebase Firestore是一个云NoSQL数据库,用于在应用程序内部添加,检索和更新数据。基本上,它是一个数据库,用于在Firebase控制台内部存储数据。 Firestore中的数据以文档的形式存储,因此可以在Firebase中轻松管理此数据。

与Firebase实时数据库相比,使用Firestore有什么好处?

与Firebase实时数据库相比,Firestore的查询更好。它具有高度的可扩展性,并且可以在Firebase Firestore中正确管理数据。在Firebase Firestore数据库内部的服务器端访问数据变得很容易。与Firebase实时数据库相比,Firebase Firestore容易得多。您可以查看有关Firebase实时数据库与Firestore数据库的更详细的指南。

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

在本文中,我们将构建一个简单的Android应用程序,在其中我们将通过一些TextField从用户那里收集数据,并将该数据发送到Firebase Cloud Firestore控制台,并且该数据将存储在Firebase数据库中。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

第2步:将您的应用连接到Firebase

创建新项目后。导航到顶部栏上的“工具”选项。在里面单击Firebase。单击Firebase后,您可以在屏幕快照中看到下面提到的右列。

在该列内,导航到Firebase Cloud Firestore。单击该选项,您将在“将应用程序连接到Firebase”和“将Cloud Firestore添加到您的应用程序”中看到两个选项。单击立即连接选项,您的应用程序将连接到Firebase。之后,单击第二个选项,现在您的应用已连接到Firebase。将您的应用程序连接到Firebase后,您将看到以下屏幕。

之后,确认已将Firebase Firestore数据库的依赖项添加到我们的Gradle文件中。导航到该文件内的应用程序> Gradle脚本。检查是否添加了以下依赖项。如果您的build.gradle文件中不存在以下依赖项。在“依赖项”部分中添加以下依赖项。

添加此依赖项后,同步您的项目,现在我们可以创建我们的应用程序了。如果您想了解有关将您的应用程序连接到Firebase的更多信息。请参阅本文以详细了解如何将Firebase添加到Android App。

步骤3:使用AndroidManifest.xml文件

要将数据添加到Firebase,我们必须授予访问Internet的权限。要添加这些权限,请导航至应用程序> AndroidManifest.xml 。在该文件内,向其添加以下权限。

XML



XML


 
    
    
 
    
    
 
    
    
 
    
    


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;
    }
}


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 Firetore 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() {
            @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();
            }
        });
    }
}


步骤4:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。

XML格式



 
    
    
 
    
    
 
    
    
 
    
    

步骤5:创建一个新的Java类来存储数据

为了将数据发送到Firebase Firestore数据库,我们必须创建一个Object类并将整个对象类发送到Firebase。要创建对象类,请导航至应用程序> Java >应用程序的包名称>右键单击它,然后单击新建> Java类>给您的类命名。在这里,我们将其命名为Courses,并在其中添加以下代码。

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;
    }
}

步骤6:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

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 Firetore 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() {
            @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();
            }
        });
    }
}

添加此代码后,请转到此链接以打开Firebase。单击此链接后,您将看到以下页面,并且在此页面上,单击右上角的“转到控制台”选项。

单击此屏幕后,您将看到下面的屏幕,其中包含您选择的项目的所有项目。

在该屏幕内,单击左侧窗口中的n Firebase Firestore数据库。

单击创建数据库选项后,您将看到以下屏幕。

在此屏幕内,我们必须选择“以测试模式启动”选项。我们正在使用测试模式,因为我们未在应用内设置身份验证。因此,我们选择在测试模式下启动。选择测试模式后,单击下一步选项,您将看到以下屏幕。

在此屏幕内,我们只需单击“启用”按钮即可启用我们的Firebase Firestore数据库。完成此过程后,我们只需运行我们的应用程序并在我们的应用程序内添加数据,然后单击“提交”按钮。您将看到在Firebase控制台中添加的数据。

以下是该应用程序的输出。

输出:

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