首頁 > Java > java教程 > 主體

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

DDD
發布: 2024-10-26 09:05:30
原創
940 人瀏覽過

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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!