Adapter.NotifyDataSetChanged doesn't work

2019-08-31 08:53发布

问题:

I have adapter for my listView and i want to update my adapter using NotifyDataSetChanged(), but it doesn't work for me. That's how I add data in my adapter:

if (Messages.Count != 0) {
    ChatAdapter = new BubbleAdapter (this, Messages);
    if(listViewChat.Adapter == null) {
        listViewChat.Adapter = ChatAdapter;
    } else {
        ChatAdapter.NotifyDataSetChanged();
    }
}

But like I said it does not work... If i update using this way, my listView is scrolling to top:

ChatAdapter = new BubbleAdapter (this, Messages);
listViewChat.Adapter = ChatAdapter;

回答1:

Try:

listViewChat.setAdapter(ChatAdapter);

You can replace the entire block with that. If the list is empty the adapter will be empty as well, and the listview will be refreshed with zero items.



回答2:

Please look at below code. You have to do similar to what I mentioned below. As I don't have your whole code snippet, so I modified the codes you mentioned:

ArrayList<MessageBubble> MessagesAll = new ArrayList<MessageBubble>();
ChatAdapter = new BubbleAdapter (this, MessagesAll);
listViewChat.setAdapter(ChatAdapter);

MessageBubble Messages = new MessageBubble();
Messages.setMessage("Hi");
if (Messages.Count != 0) {
    MessagesAll.add(Messages);
    ChatAdapter.notifyDataSetChanged();
}

Plase let me know if you still not succeeded.



回答3:

Use ChatAdapter.notifyDataSetInvalidated(); instead of ChatAdapter.notifyDataSetChanged();



回答4:

First and foremost, I would like to thank each and everyone of the contributors of stack. I'm sure I owe you more gratitude than I can give.

This question has taken way too much of my time. For the folks that are still looking for a solution:

  1. the performFilter should remain as is.

  2. the publishResults should be as simple as:

    mIngredientList = (ArrayList) results.values; adapter.clear(); if (mIngredientList != null) { for (int i = 0; i < mIngredientList.size(); i++) adapter.add(mIngredientList.get(i)); }

  3. the trick is this: public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    mIngredientAdapter.getFilter().filter(charSequence.toString()); mItemList.setAdapter(mIngredientAdapter); } Not re-adding the adapter, doesn't seem to work.