我有一个位置的给定用户的聊天室列表,以及另一个位置给定聊天室的消息总数.我想跟踪用户所在的聊天室的一些消息.
我有以下片段:
//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) { } }); } } //...... }
问题是,如何删除所有这些ValueEventListener以后,当onChildRemoved将被调用,或者我不再需要它们了?
处理这种情况的建议方法是什么?我应该在HashMap中存储子键和监听器,并自己跟踪它们,还是有一些方法来删除给定firebase位置的所有侦听器?
解决方法
数据认真的方式是创建一个ValueEventListeners的HashMap,然后在onStop或onDestroy中删除这些监听器.
为了保持简单,您应该使用单个事件监听器来获取房间.然后,对于每个房间,您可以创建一个实时监听器.
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); } } }