设计和了解如何从 Firebase 数据库中检索实时数据

此示例假定你已设置 Firebase 实时数据库。如果你是初学者,请在此处告知如何将 Firebase 添加到你的 Android 项目中。

首先,将 Firebase 数据库的依赖项添加到应用程序级 build.gradle 文件中:

compile 'com.google.firebase:firebase-database:9.4.0'

现在,让我们创建一个聊天应用程序,将数据存储到 Firebase 数据库中。

第 1 步:创建一个名为 Chat 的类

只需创建一个包含聊天所需的一些基本变量的类:

public class Chat{
    public String name, message;
}

第 2 步:创建一些 JSON 数据

要向/从 Firebase 数据库发送/检索数据,你需要使用 JSON。让我们假设一些聊天已经存储在数据库的根级别。这些聊天的数据可能如下所示:

[
    {
        "name":"John Doe",
        "message":"My first Message"
    },
    {
        "name":"John Doe",
        "message":"Second Message"
    },
    {
        "name":"John Doe",
        "message":"Third Message"
    }
]

第 3 步:添加侦听器

有三种类型的监听器。在下面的例子中,我们将使用 childEventListener

DatabaseReference chatDb = FirebaseDatabase.getInstance().getReference() // Referencing the root of the database.
        .child("chats"); // Referencing the "chats" node under the root.

chatDb.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        // This function is called for every child id chat in this case, so using the above
        // example, this function is going to be called 3 times.
        
        // Retrieving the Chat object from this function is simple.
        Chat chat; // Create a null chat object.

        // Use the getValue function in the dataSnapshot and pass the object's class name to
        // which you want to convert and get data. In this case it is Chat.class.
        chat = dataSnapshot.getValue(Chat.class);

        // Now you can use this chat object and add it into an ArrayList or something like
        // that and show it in the recycler view.
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        // This function is called when any of the node value is changed, dataSnapshot will
        // get the data with the key of the child, so you can swap the new value with the
        // old one in the ArrayList or something like that.

        // To get the key, use the .getKey() function.
        // To get the value, use code similar to the above one.
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        // This function is called when any of the child node is removed. dataSnapshot will
        // get the data with the key of the child.

        // To get the key, use the s String parameter .
    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        // This function is called when any of the child nodes is moved to a different position.

        // To get the key, use the s String parameter.
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // If anything goes wrong, this function is going to be called.

        // You can get the exception by using databaseError.toException();
    }
});

第 4 步:将数据添加到数据库

只需创建一个 Chat 类对象并按如下方式添加值:

Chat chat=new Chat();
chat.name="John Doe";
chat.message="First message from android";

现在获取对检索会话中的聊天节点的引用:

DatabaseReference chatDb = FirebaseDatabase.getInstance().getReference().child("chats");

在开始添加数据之前,请记住,你需要一个更深入的引用,因为聊天节点有更多节点,添加新聊天意味着添加包含聊天详细信息的新节点。我们可以使用 DatabaseReference 对象上的 push() 函数生成一个新的唯一的节点名称,该函数将返回另一个 DatabaseReference,而 DatabaseReference 又指向一个新形成的节点来插入聊天数据。

// The parameter is the chat object that was newly created a few lines above.
chatDb.push().setValue(chat);

setValue() 函数将确保调用所有应用程序的 onDataChanged 函数(包括相同的设备),这恰好是聊天节点的附加侦听器。