📌  相关文章
📜  如何在Android中将数据保存到Firebase实时数据库?

📅  最后修改于: 2021-05-10 14:36:46             🧑  作者: Mango

Firebase是著名的后端平台之一,许多开发人员使用Firebase为其应用程序和网站提供后端支持。它是Google的产品,可提供数据库,存储,用户身份验证等服务。在本文中,我们将创建一个简单的应用程序,在该应用程序中,我们会将数据添加到Firebase实时数据库中。注意,我们将使用Java语言实现该项目。

什么是Firebase实时数据库?

Firebase Realtime Database是一个NoSQL云数据库,用于存储和同步数据。来自数据库的数据可以一次在所有客户端(例如android,web以及IOS)之间同步。数据库中的数据以JSON格式存储,并随每个连接的客户端实时更新。

使用Firebase实时数据库有哪些优势?

  • 使用Firebase Realtime数据库的主要优点是,数据以实时方式进行更新,您无需对数据更新或更改提出任何请求。每次数据更改时,数据库都会使用数据同步,这些更改将在几毫秒内反映出所连接的用户。
  • 使用Firebase Realtime Database时,即使设备失去与数据库的连接,您的应用程序仍可以保持响应。用户建立连接后,他将从数据库中接收对数据所做的更改。
  • 可通过Firebase的Web门户轻松访问存储在Firebase数据库中的数据。您可以从PC以及移动设备管理数据库。您可以管理数据库规则,该规则授予对数据库进行读写操作的权限。

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

在本文中,我们将构建一个简单的应用程序,在该应用程序中,我们将借助一些TextField从用户那里获取数据,并将该数据存储在Firebase Realtime Database中。请注意,我们正在使用Firebase Realtime Database,并且该应用程序是使用Java语言编写的。

分步实施

步骤1:创建一个新项目

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

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

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

在该列内,导航到Firebase Realtime Database 。单击该选项,您将在“将应用程序连接到Firebase”和“将Firebase实时数据库添加到您的应用程序”中看到两个选项。单击立即连接,您的应用程序将连接到Firebase。之后,单击第二个选项,现在您的应用已连接到Firebase。

将您的应用程序连接到Firebase后,您将看到以下屏幕。

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

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

步骤3:使用AndroidManifest.xml文件

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

XML


XML


  
    
    
  
    
    
  
    
    
  
    
    


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


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 weather 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();
            }
        });
    }
}


步骤4:使用activity_main.xml文件

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

XML格式



  
    
    
  
    
    
  
    
    
  
    
    

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

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

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

步骤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.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 weather 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();
            }
        });
    }
}

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

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

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

单击此选项后,您将看到右侧的屏幕。在此页面上,单击顶部栏中的“规则”选项。您将看到以下屏幕。

在此屏幕内,单击“规则”选项卡,您将看到上面的屏幕,并将规则更改为true,如屏幕截图所示。规则已更改为true,因为我们未在应用程序内部提供身份验证,并且必须将数据写入数据库。这就是为什么我们将其指定为true。更改规则后,单击“发布规则”按钮。单击该选项,您的规则将被发布。现在回到数据库的“数据”选项卡。

输出:

以下是我们用于将数据添加到Firebase实时数据库的应用程序的视频。

运行该应用程序,并确保将您的设备连接到互联网。之后,在您的文本字段中添加一些数据,然后单击“插入数据”按钮。数据将被添加到我们的Firebase数据库中。以下是将数据从应用程序添加到Firebase数据库后,我们将看到的屏幕截图。

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