我正在将Firebase数据库用于我的聊天应用程序。我想同时在fire base数据库的三个位置插入数据,并且要获取数据,我添加了addValueEventListener,因为我想在每次数据更改时都在数据中,但是此Listener多次重新打开我当前的聊天活动,请指导我可以我会解决此问题。谢谢* 这是我获取数据的代码:
private void getAllMessages(String location) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("conversations");
rootRef.child(location).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
get_message_list = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
UserChat userChat = ds.getValue(UserChat.class);
UserChat userChat1 = new UserChat();
String f_id = userChat.fromID;
String content = userChat.content;
String to_id = userChat.toID;
String type = userChat.type;
int timestamp1 = userChat.timestamp;
userChat1.setContent(content);
userChat1.setFromID(f_id);
userChat1.setToID(to_id);
userChat1.setType(type);
get_message_list.add(userChat1);
}
Log.e("CHECK_RUN", " COUNT");
if (adaper == null) {
adaper = new GetChatAdapter(ChatActivity.this, get_message_list);
get_chat_recycler_view.setLayoutManager(new LinearLayoutManager(ChatActivity.this, LinearLayoutManager.VERTICAL, false));
get_chat_recycler_view.setAdapter(adaper);
get_chat_recycler_view.scrollToPosition(get_message_list.size() - 1);
adaper.notifyDataSetChanged();
} else {
adaper.notifyDataSetChanged();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}