Reputation:
I am developing a simple chat application and i followed this tutorial https://youtu.be/IHHLyeak46E to create this chat. But i am facing a problem with my dataSnapshot. I have deployed the app on 2 phones. But what happens is, when the Datasnapshot detects changes in the database, it doesn't update my listview with only my recent chat but together with previous messages already in the chat and i end up having duplicated messages. In the tutorial, it worked fine. I don't really know if it is because of the foreach loop. Why is this happening?
public void OnDataChange(DataSnapshot snapshot)
{
var items = snapshot.Child("key")?.Child("users id")?.Children?.ToEnumerable<DataSnapshot>();
HashMap map;
foreach(DataSnapshot item in items){
map = (HashMap)item.Value;
allMessages.Add(new EventMessageContent(map.Get("username")?.ToString(), map.Get("content")?.ToString()));
}
CommentViewAdapter adapter = new CommentViewAdapter(this, allMessages);
allMessages.Adapter = adapter;
}
Upvotes: 0
Views: 1036
Reputation:
You would need to clear your list on every update.
public void OnDataChange(DataSnapshot snapshot)
{
allMessages.clear();
var items = snapshot.Child("key")?.Child("users id")?.Children?.ToEnumerable<DataSnapshot>();
HashMap map;
foreach(DataSnapshot item in items){
map = (HashMap)item.Value;
allMessages.Add(new EventMessageContent(map.Get("username")?.ToString(), map.Get("content")?.ToString()));
}
CommentViewAdapter adapter = new CommentViewAdapter(this, allMessages);
allMessages.Adapter = adapter;
}
Upvotes: 1