設計和了解如何從 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 函式(包括相同的裝置),這恰好是聊天節點的附加偵聽器。