在我的聊天应用中,我想收到某人发送的每条新消息(最后的消息)。
但是,当我在我的应用中附加ChildEventListener
时,onChildAdded()
会被调用两次。
以下是代码:
chatRoomLastMessageUpdateReference = FirebaseDatabase.getInstance().getReference().
child(Constants.FIRE_BASE_PATH_CHAT_ROOMS).child(roomKey);
chatRoomLastMessageChildListener = mChatHelper
.getLastMessage(mAdapterChat, chatRoomLastMessageUpdateReference, mRecyclerChat);
chatRoomLastMessageUpdateReference
.addChildEventListener(chatRoomLastMessageChildListener);
方法getLastMessage()
:
public ChildEventListener getLastMessage(final AdapterChat mAdapterChat, final DatabaseReference pollRoomLastMessageUpdateReference, final RecyclerView mRecyclerChat) {
Query queryLastMessage = pollRoomLastMessageUpdateReference.orderByKey().limitToLast(1);
ChildEventListener childEventListener = queryLastMessage.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Message message = dataSnapshot.getValue(Message.class);
Log.d("message", "onChildAdded: " + message.getMessage());
mAdapterChat.updateLastMessage(message);
mRecyclerChat.getLayoutManager().scrollToPosition(mAdapterChat.getMessagesObekt().size() - 1);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return childEventListener;
}
这里是ChildEventListener
分离:
@Override
protected void onDestroy() {
super.onDestroy();
if (chatRoomLastMessageChildListener != null) {
chatRoomLastMessageUpdateReference.removeEventListener(chatRoomLastMessageChildListener);
}
}
这是登录onChildAdded()
方法,该方法在用户发送新聊天消息后调用。我发送了3条消息,因为您看到每条消息都被调用了两次
05-29 09:55:38.000 30212-30212/com.example.petar.votemeup D/message: onChildAdded: called message1
05-29 09:55:38.001 30212-30212/com.example.petar.votemeup D/message: onChildAdded: called message1
05-29 09:55:40.382 30212-30212/com.example.petar.votemeup D/message: onChildAdded: called message2
05-29 09:55:40.384 30212-30212/com.example.petar.votemeup D/message: onChildAdded: called message2
05-29 09:55:42.954 30212-30212/com.example.petar.votemeup D/message: onChildAdded: called message3
05-29 09:55:42.955 30212-30212/com.example.petar.votemeup D/message: onChildAdded: called message3

更新更新
有趣的是,当我没有附加ChildEventListener时,一切都很好。 但是,我现在不明白,如果我不附加它,我将如何分离ChildEventListener。 所以,当我这样做的时候,一切都很好
chatRoomLastMessageUpdateReference = FirebaseDatabase.getInstance().getReference().
child(Constants.FIRE_BASE_PATH_CHAT_ROOMS).child(roomKey);
chatRoomLastMessageChildListener = mChatHelper.getLastMessage(mAdapterChat, chatRoomLastMessageUpdateReference, mRecyclerChat);
//i remove this line of code below, its working but, i feel that this is not the correct
//chatRoomLastMessageUpdateReference.addChildEventListener(chatRoomLastMessageChildListener);