I implemented a messaging system for my android application. Here is how it works :
The problem that I'm facing is that sometimes the message send by the user is displayed twice. I think that I understand the problem : the polling gets the new added message as not already in the listview and add it to the listview adapter. Is there a way to avoid that behaviour?
Here is how I checked if the polled message is already in the adapter :
public class MessageListViewAdapter : BaseAdapter
{
List<Model.Message> messages = new List<Model.Message>();
Context context;
public MessageListViewAdapter(Context context,List<Model.Message> messages)
{
this.context = context;
this.messages = messages;
}
public void add(Model.Message message)
{
if (!messages.Contains(message))
{
this.messages.Add(message);
NotifyDataSetChanged(); // to render the list we need to notify
}
}
public override int Count =>messages.Count;
public override Java.Lang.Object GetItem(int position)
{
return null;
}
public override long GetItemId(int position)
{
return position;
}
Let me know if you need other informations, maybe my explanation is not clear or not complete enough. Thanks in advance,
Lio
What you should do is separate the listview from the storage of the messages.
Instead of putting items into a listview, you should maintain a list of messages in an array. When you type a message you can add it to the array, along with a date time stamp or GUID. When you poll, you also add entries to the array if they don't exist. Create a method called AddItemToListView()
or similar to do this
Then keep population of the list view separate - create a method called UpdateListView()
and call it after polling and after you type a message and add it.
Inside AddItemToListView()
you can put logic to check if the item is already in the list, and if it is, don't add it. By either comparing the date time, or the GUID.
I would definitely check the Date or a GUID to compare messages because anything else is not reliable, especially object comparisons which is what it looks like you're doing.