Java – how to track listeners in firebase on Android?
I have a list of chat rooms for a given user in one location and the total number of messages for a given chat room in another location I want to track some messages in the chat room where users are
I have the following clips:
//getting all chat rooms this user belongs to mFirebase.child("myChatRooms").child("testUser").addChildEventListener(new ChildEventListener() { @Override public void onChildAdded (DataSnapshot dataSnapshot,String prevIoUsKey){ for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { ChatRoom myRoom = postSnapshot.getValue(ChatRoom.class); //listening to message count in every chat room user belongs to mFirebase.child("chatRoomMessageCount").child(postSnapshot.getKey()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //number of messages have changed } @Override public void onCancelled(FirebaseError firebaseError) { } }); } } //...... }
The question is, how can onchildremoved be called after deleting all these valueeventlisteners, or do I no longer need them?
What is the recommended way to deal with this situation? Should I store subkeys and listeners in the HashMap and track them myself, or are there ways to delete all listeners at a given firebase location?
Solution
The way to get serious data is to create a HashMap of valueeventlisteners, and then delete these listeners in onstop or ondestroy
To keep things simple, you should use a single event listener to get rooms Then, for each room, you can create a live listener
public class MainActivity extends Activity { private Firebase mRef; private HashMap<Firebase,ValueEventListener> mListenerMap; @Override protected void onStart() { super.onStart(); mRef = new Firebase("https://<your-firebase-app>/myChatRooms/testUser"); mRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) { ValueEventListener listener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // do your thing here } @Override public void onCancelled(FirebaseError firebaseError) { } }; mListenerMap.put(postSnapshot.getRef(),listener); Firebase childRef = mRef.child("chatRoomMessageCount").child(postSnapshot.getKey()); childRef.addValueEventListener(listener); } } @Override public void onCancelled(FirebaseError firebaseError) { } }); } @Override protected void onStop() { super.onStop(); for (Map.Entry<Firebase,ValueEventListener> entry : mListenerMap.entrySet()) { Firebase ref = entry.getKey(); ValueEventListener listener = entry.getValue(); ref.removeEventListener(listener); } } }