在FirebaseUI-Android RecyclerView 中新增和刪除快照偵聽器
FirebaseUI-Android 提供了一種使用即時資料填充RecyclerView 的RecyclerView 的便捷方法消防店。但是,了解如何正確新增和刪除快照監聽器以避免資源洩漏非常重要。
新增快照監聽器
使用 FirebaseRecyclerAdapter 時,會新增一個監聽器RecyclerView 中的每個項目。在 populateViewHolder 方法中,您可以使用 getRef(i) 方法來擷取目前專案的 DocumentReference。
要監聽引用的更改,您可以使用 addSnapshotListener(EventListener) 方法。此方法採用 EventListener 作為參數,只要引用的快照發生更改,就會呼叫此方法。
刪除快照偵聽器
刪除偵聽器至關重要當不再需要它時。如果不這樣做將導致內存洩漏。您可以使用ListenerRegistration物件上的remove()方法刪除監聽器。
populateViewHolder方法中的實作
以下是如何新增和刪除快照的範例FirebaseRecyclerAdapter 的populateViewHolder 方法中的偵聽器:
在此範例中,listenerRegistration 變數初始化為null。然後,在 if 語句中,如果尚未新增監聽器,則將其新增。@Override protected void populateViewHolder(final ConvViewHolder convViewHolder, final Conv conv, int i) { final String list_user_id = getRef(i).getKey(); final DocumentReference docRef = db.collection("cities").document(list_user_id); ListenerRegistration listenerRegistration = null; if (listenerRegistration == null) { listenerRegistration = docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException e) { if (e != null) { Log.w(TAG, "Listen failed.", e); return; } if (snapshot != null && snapshot.exists()) { Log.d(TAG, "Current data: " + snapshot.getData()); } else { Log.d(TAG, "Current data: null"); } } }); } }
要在以下情況下刪除監聽器: Activity 不再可見,您可以重寫Activity 中的onStop( ) 方法,並呼叫ListenerRegistration 上的remove() 方法。
透過執行以下步驟,您可以確保快照偵聽器正確新增和刪除,防止資源洩漏並提高應用程式的效能。@Override protected void onStop() { super.onStop(); if (listenerRegistration != null) { listenerRegistration.remove(); } }
以上是在FirebaseUI-Android RecyclerView中使用快照監聽器時如何避免資源外洩?的詳細內容。更多資訊請關注PHP中文網其他相關文章!