在 Android 上使用資料清單

本文件介紹如何在 Firebase 中使用資料清單。如要瞭解讀取及寫入 Firebase 資料的基本概念,請參閱「在 Android 上讀取及寫入資料」。

取得 DatabaseReference

如要從資料庫讀取及寫入資料,您需要 DatabaseReference 的執行個體:

Kotlin+KTX

private lateinit var database: DatabaseReference
// ...
database = Firebase.database.reference

Java

private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();

讀取及寫入清單

附加至資料清單

使用 push() 方法,將資料附加至多使用者應用程式中的清單。每當在指定的 Firebase 參考資料中加入新的子項時,push() 方法就會產生專屬金鑰。透過針對清單中的每個新元素使用自動產生的金鑰,多個用戶端即可同時將子項新增至相同位置,而不會發生寫入衝突。push() 產生的不重複索引鍵是根據時間戳記,因此清單項目會自動依時間排序。

您可以參照 push() 方法傳回新資料的參照,取得子項自動產生的鍵值,或為子項設定資料。對 push() 參照呼叫 getKey() 會傳回自動產生的金鑰值。

您可以使用這些自動產生的金鑰來簡化資料結構。詳情請參閱資料擴散傳遞範例

監聽子事件

使用清單時,應用程式應監聽子項事件,而不是單一物件使用的值事件。

如果作業發生在節點子項所發生的特定作業,例如透過 push() 方法新增的子項,或透過 updateChildren() 方法更新的子項,就會觸發子項事件。這兩個組合都有助於監聽資料庫中特定節點的變更。

為了監聽 DatabaseReference 上的子事件,請附加 ChildEventListener

監聽器 事件回呼 一般用量
ChildEventListener onChildAdded() 擷取項目清單,或監聽附加項目清單。 每個現有子項都會觸發一次回呼,之後每次將新子項新增至指定路徑時,就會再次觸發回呼。傳遞至事件監聽器的 DataSnapshot 包含新子項的資料。
onChildChanged() 監聽清單中項目的變更。每當變更子節點 (包括對子節點子系的任何修改) 時,都會觸發這個事件。傳遞至事件監聽器的 DataSnapshot 包含子項的更新資料。
onChildRemoved() 監聽已從清單中移除的項目。傳遞至事件回呼的 DataSnapshot 包含已移除子項的資料。
onChildMoved() 監聽已排序清單中項目順序的變更。 只要更新觸發了子項重新排序的更新作業,進而觸發 onChildChanged() 回呼,就會觸發這個事件。可與依 orderByChildorderByValue 排序的資料搭配使用。

舉例來說,社交網誌應用程式可以搭配使用下列方法,監控貼文留言中的活動,如下所示:

Kotlin+KTX

val childEventListener = object : ChildEventListener {
    override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) {
        Log.d(TAG, "onChildAdded:" + dataSnapshot.key!!)

        // A new comment has been added, add it to the displayed list
        val comment = dataSnapshot.getValue<Comment>()

        // ...
    }

    override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) {
        Log.d(TAG, "onChildChanged: ${dataSnapshot.key}")

        // A comment has changed, use the key to determine if we are displaying this
        // comment and if so displayed the changed comment.
        val newComment = dataSnapshot.getValue<Comment>()
        val commentKey = dataSnapshot.key

        // ...
    }

    override fun onChildRemoved(dataSnapshot: DataSnapshot) {
        Log.d(TAG, "onChildRemoved:" + dataSnapshot.key!!)

        // A comment has changed, use the key to determine if we are displaying this
        // comment and if so remove it.
        val commentKey = dataSnapshot.key

        // ...
    }

    override fun onChildMoved(dataSnapshot: DataSnapshot, previousChildName: String?) {
        Log.d(TAG, "onChildMoved:" + dataSnapshot.key!!)

        // A comment has changed position, use the key to determine if we are
        // displaying this comment and if so move it.
        val movedComment = dataSnapshot.getValue<Comment>()
        val commentKey = dataSnapshot.key

        // ...
    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.w(TAG, "postComments:onCancelled", databaseError.toException())
        Toast.makeText(
            context,
            "Failed to load comments.",
            Toast.LENGTH_SHORT,
        ).show()
    }
}
databaseReference.addChildEventListener(childEventListener)

Java

ChildEventListener childEventListener = new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());

        // A new comment has been added, add it to the displayed list
        Comment comment = dataSnapshot.getValue(Comment.class);

        // ...
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());

        // A comment has changed, use the key to determine if we are displaying this
        // comment and if so displayed the changed comment.
        Comment newComment = dataSnapshot.getValue(Comment.class);
        String commentKey = dataSnapshot.getKey();

        // ...
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());

        // A comment has changed, use the key to determine if we are displaying this
        // comment and if so remove it.
        String commentKey = dataSnapshot.getKey();

        // ...
    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
        Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());

        // A comment has changed position, use the key to determine if we are
        // displaying this comment and if so move it.
        Comment movedComment = dataSnapshot.getValue(Comment.class);
        String commentKey = dataSnapshot.getKey();

        // ...
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.w(TAG, "postComments:onCancelled", databaseError.toException());
        Toast.makeText(mContext, "Failed to load comments.",
                Toast.LENGTH_SHORT).show();
    }
};
databaseReference.addChildEventListener(childEventListener);

監聽價值事件

雖然建議使用 ChildEventListener 讀取資料清單,但在某些情況下,將 ValueEventListener 附加至清單參照會很有用。

ValueEventListener 附加至資料清單後,系統會傳回整份資料清單做為單一 DataSnapshot,方便您透過迴圈的方式存取個別子項。

即使查詢只有一個符合項目,快照仍是一個清單,它只會包含一個項目。如要存取該項目,您需要循環處理結果:

Kotlin+KTX

// My top posts by number of stars
myTopPostsQuery.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        for (postSnapshot in dataSnapshot.children) {
            // TODO: handle the post
        }
    }

    override fun onCancelled(databaseError: DatabaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
        // ...
    }
})

Java

// My top posts by number of stars
myTopPostsQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
            // TODO: handle the post
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
});

如果您想在單一作業中擷取清單的所有子項,而不想監聽其他 onChildAdded 事件,這種模式就能派上用場。

卸離事件監聽器

如要移除回呼,請對 Firebase 資料庫參考資料呼叫 removeEventListener() 方法。

如果已在資料位置中多次新增事件監聽器,系統會針對每個事件多次呼叫該事件監聽器,因此您必須按照相同的次數卸離,才能完全移除事件監聽器。

對父項事件監聽器呼叫 removeEventListener() 不會自動移除在其子節點上註冊的事件監聽器;此外,您也必須在任何子項事件監聽器上呼叫 removeEventListener(),才能移除回呼。

排序及篩選資料

您可以使用即時資料庫 Query 類別,擷取依鍵、值或子項值排序的資料。您也可以篩選排序結果,以達到特定結果數量、鍵/值範圍。

排序資料

如要擷取經過排序的資料,請先指定一種依順序排序的方法來決定結果的排序方式:

方式 用量
orderByChild() 按指定子項鍵或巢狀子路徑的值排序結果。
orderByKey() 按子項鍵排序結果。
orderByValue() 按照子項值排序結果。

一次只能使用「一個」排序方法。在同一查詢中多次呼叫依順序的方法呼叫會擲回錯誤。

以下範例說明如何擷取使用者最受歡迎的貼文清單 (依星級評等排序):

Kotlin+KTX

// My top posts by number of stars
val myUserId = uid
val myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
    .orderByChild("starCount")

myTopPostsQuery.addChildEventListener(object : ChildEventListener {
    // TODO: implement the ChildEventListener methods as documented above
    // ...
})

Java

// My top posts by number of stars
String myUserId = getUid();
Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId)
        .orderByChild("starCount");
myTopPostsQuery.addChildEventListener(new ChildEventListener() {
    // TODO: implement the ChildEventListener methods as documented above
    // ...
});

此方法會定義一項查詢,在與子事件監聽器結合時,會根據使用者 ID 排序用戶端,與資料庫中的使用者貼文同步處理,並依照每則貼文獲得的星星數量排序。使用 ID 做為索引鍵的技術稱為資料擴散傳遞,詳情請參閱建立資料庫結構

orderByChild() 方法的呼叫會指定子項鍵,依結果排序結果。在這種情況下,貼文會按照各自的 "starCount" 子項值排序。若您有類似以下的資料,查詢也可以按巢狀子項排序:

"posts": {
  "ts-functions": {
    "metrics": {
      "views" : 1200000,
      "likes" : 251000,
      "shares": 1200,
    },
    "title" : "Why you should use TypeScript for writing Cloud Functions",
    "author": "Doug",
  },
  "android-arch-3": {
    "metrics": {
      "views" : 900000,
      "likes" : 117000,
      "shares": 144,
    },
    "title" : "Using Android Architecture Components with Firebase Realtime Database (Part 3)",
    "author": "Doug",
  }
},

在這個範例中,我們可以透過在 orderByChild() 呼叫中指定巢狀子項的相對路徑,依照 metrics 鍵底下巢狀的值來排序清單元素。

Kotlin+KTX

// Most viewed posts
val myMostViewedPostsQuery = databaseReference.child("posts")
    .orderByChild("metrics/views")
myMostViewedPostsQuery.addChildEventListener(object : ChildEventListener {
    // TODO: implement the ChildEventListener methods as documented above
    // ...
})

Java

// Most viewed posts
Query myMostViewedPostsQuery = databaseReference.child("posts")
        .orderByChild("metrics/views");
myMostViewedPostsQuery.addChildEventListener(new ChildEventListener() {
    // TODO: implement the ChildEventListener methods as documented above
    // ...
});

如要進一步瞭解其他資料類型的排序方式,請參閱「查詢資料的排序方式」。

篩選資料

如要篩選資料,您可以在建構查詢時,將任何限製或範圍方法與排序方法結合。

方式 用量
limitToFirst() 設定要從已排序結果清單開頭傳回的項目數量上限。
limitToLast() 設定從已排序結果清單結尾傳回的項目數量上限。
startAt() 依據所選的順序,傳回大於或等於指定鍵或值的項目。
startAfter() 視所選方法而定,傳回大於指定鍵或值的項目。
endAt() 依據所選的順序,傳回小於或等於指定鍵或值的項目。
endBefore() 視所選的順序而定,傳回小於指定鍵或值的項目。
equalTo() 根據所選順序,傳回與指定鍵或值相等的項目。

有別於依序執行排序的方式,您可以合併多個限製或範圍函式。舉例來說,您可以結合 startAt()endAt() 方法,將結果限制為指定範圍內的值。

即使查詢只有一個相符結果,快照仍為清單,只是只包含一個項目。如要存取項目,就必須循環處理結果:

Kotlin+KTX

// My top posts by number of stars
myTopPostsQuery.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        for (postSnapshot in dataSnapshot.children) {
            // TODO: handle the post
        }
    }

    override fun onCancelled(databaseError: DatabaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
        // ...
    }
})

Java

// My top posts by number of stars
myTopPostsQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
            // TODO: handle the post
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        // Getting Post failed, log a message
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        // ...
    }
});

限制結果數量

您可以使用 limitToFirst()limitToLast() 方法,設定特定回呼要同步處理的子項數量上限。舉例來說,如果您使用 limitToFirst() 將限制設為 100,一開始最多只會接收 100 個 onChildAdded() 回呼。如果 Firebase 資料庫中儲存的項目少於 100 個,則每個項目都會觸發 onChildAdded() 回呼。

當項目有變更時,您也會收到輸入查詢的項目 onChildAdded() 回呼,而針對移出查詢的項目,您會收到 onChildRemoved() 回呼,因此總數會維持在 100。

以下範例展示網誌應用程式如何定義查詢,以擷取所有使用者最新發布的 100 篇文章清單:

Kotlin+KTX

// Last 100 posts, these are automatically the 100 most recent
// due to sorting by push() keys.
databaseReference.child("posts").limitToFirst(100)

Java

// Last 100 posts, these are automatically the 100 most recent
// due to sorting by push() keys
Query recentPostsQuery = databaseReference.child("posts")
        .limitToFirst(100);

這個範例僅定義查詢,如要實際同步處理資料,該查詢需要有附加的事件監聽器

依鍵或值篩選

您可以使用 startAt()startAfter()endAt()endBefore()equalTo(),為查詢選擇任意的開始、結束和等定點。這有助於分頁資料,或尋找具有特定值的子項項目。

查詢資料的排序方式

本節說明 Query 類別中各個排序方法如何排序資料。

orderByChild

使用 orderByChild() 時,包含指定子項鍵的資料會按照以下順序排序:

  1. 針對指定子項金鑰,具有 null 值的子項會先列出。
  2. 指定子項金鑰值為 false 的子項接著會顯示。如果多個子項的值為 false,則這些子項的值會按照鍵字母順序排序。
  3. 指定子項金鑰值為 true 的子項接著會顯示。如果多個子項的值為 true,就會按照鍵的字母順序排序。
  4. 含有數值的子項接著會以遞增順序排序。如果指定的子節點有多個子項具有相同數值,系統會按照索引鍵排序。
  5. 字串是由數字後方,並按遞增順序排列。如果指定的子節點有多個子項的值相同,就會按照鍵的字母順序排列。
  6. 物件在最後,且依索引鍵順序排列,以遞增順序排列。

orderByKey

使用 orderByKey() 排序資料時,系統會依鍵以遞增順序傳回資料。

  1. 如果子項的索引鍵可剖析為 32 位元整數,其內容會先以遞增順序排序。
  2. 具有字串值做為索引鍵的下一個子項,並依字母順序遞增排序。

orderByValue

使用 orderByValue() 時,子項會按照值的順序排列。排序條件與 orderByChild() 相同,但會使用節點的值而非指定子項鍵的值。

後續步驟