首頁  >  文章  >  Java  >  如何透過 FirebaseFirestore 查詢在 RecyclerView 項目的「populateViewHolder」方法中使用「addSnapshotListener」和「remove」?

如何透過 FirebaseFirestore 查詢在 RecyclerView 項目的「populateViewHolder」方法中使用「addSnapshotListener」和「remove」?

DDD
DDD原創
2024-10-26 09:05:30921瀏覽

How to Use `addSnapshotListener` and `remove` in a RecyclerView Item's `populateViewHolder` Method with a FirebaseFirestore Query?

在RecyclerView Item的PopulateViewHolder中使用addSnapshotListener和remove

問題:

問題:

問題:

FirebaseUI-Android 庫注意事項:

FirebaseUI-Android 庫中的 FirebaseRecyclerAdapter 處理 RecyclerView 的資料變更通知。但是,這不支援使用 addSnapshotListener 來填入視圖持有者。

    使用EventListener 和全域變數:
  1. 要在populateViewHolder 中使用addSnapshotListener,請依照下列步驟操作:
    <code class="java">EventListener<DocumentSnapshot> eventListener;</code>
  2. 聲明一個全域EventListener變數:

    <code class="java">eventListener = new EventListener<DocumentSnapshot>() {
     @Override
     public void onEvent(DocumentSnapshot snapshot, FirebaseFirestoreException e) {
         if (e != null) {
             Log.w(TAG, "Listen failed.", e);
             return;
         }
    
         if (snapshot != null && snapshot.exists()) {
             // Do what you need to do
         }
     }
    };
    if (listenerRegistration == null) {
     listenerRegistration = yourRef.addSnapshotListener(eventListener);
    }</code>
  3. 初始化監聽器並且加入populateViewHolder:

    <code class="java">@Override
    protected void onStop() {
     if (listenerRegistration != null) {
         listenerRegistration.remove();
     }
    }</code>
  4. <code class="java">@Override
    protected void onStart() {
     super.onStart();
     if (listenerRegistration == null) {
         listenerRegistration = yourRef.addSnapshotListener(eventListener);
     }
    }</code>
    在onStart() 中再次加入監聽器:

  • 替代選項:
如果不需要即時更新數據,可以考慮使用get()。這會讀取文件一次,並且不需要偵聽器。 您也可以透過將活動作為第一個參數傳遞給 addSnapshotListener 來手動刪除偵聽器。當 Activity 停止時,Firestore 將自動清理監聽器。

以上是如何透過 FirebaseFirestore 查詢在 RecyclerView 項目的「populateViewHolder」方法中使用「addSnapshotListener」和「remove」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn