我正在尝试显示用户从Firebase Database
获得的最后一次会话列表。我正在使用嵌套的ValueEventListeners
,以便我首先检索当前用户所涉及的chatroom IDs
,然后根据这些ID,我获得最新的活动(来自该聊天室)并相应地创建一个对象被添加到ListView。
创建片段后,chatRooms列表已正确加载,如here所示。然而,如果另一个用户向当前用户发送另一条消息,最后一个项目会重复(不知何故,它会获得上一个标记,但最新消息中的文本相同),如here所示。
导致此行为的原因是什么?
MyChatsFragment.java
public class MyChatsFragment extends Fragment {
private ListView listView;
public MyChatsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_chats, container, false);
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference databaseReference = database.getReference();
final DatabaseReference ChatMembersReference = databaseReference.child("chat_members");
final FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if (currentUser != null) {
final String currentUID = currentUser.getUid();
listView = (ListView) view.findViewById(R.id.MyChatsList);
Query filterQuery = ChatMembersReference.orderByChild(currentUID).equalTo(true);
filterQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final List<ChatInfo> my_chats = new ArrayList<ChatInfo>();
for (DataSnapshot child : dataSnapshot.getChildren()) {
final String ChatRoom = child.getKey();
// ADD VALUE EVENT LISTENER
databaseReference.child("chat_info").child(ChatRoom).child("lastStamp").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long lastMessageStamp = (long) dataSnapshot.getValue();
ChatInfo currentChatInfo = new ChatInfo(ChatRoom, lastMessageStamp);
my_chats.add(currentChatInfo);
// HERE WE HAVE TO SORT
if (my_chats.size() > 1) {
Collections.sort(my_chats, new Comparator<ChatInfo>() {
@Override
public int compare(ChatInfo o1, ChatInfo o2) {
if (o1.getLastMessageTimeStamp() < o2.getLastMessageTimeStamp()) {
return -1;
} else if (o1.getLastMessageTimeStamp() > o2.getLastMessageTimeStamp()) {
return 1;
}
return 0;
}
});
}
Collections.reverse(my_chats);
MyChatsAdapter myChatsAdapter = new MyChatsAdapter(getActivity(), my_chats);
listView.setAdapter(myChatsAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
return view;
}
}
MyChatsAdapter.java :check this gist please