Android Array Adapter with ArrayList and ListView not updating when the arraylist is changed

前端 未结 3 431
一个人的身影
一个人的身影 2021-02-04 10:52

I have an android app with a screen that comprises of a ListView, which I am using to display a list of devices. These devices are held in an array.

I am trying to use

3条回答
  •  逝去的感伤
    2021-02-04 11:11

    While the accepted answer solves the problem, the explanation of why is incorrect, and since this is an important concept I thought I'd attempt to clarify.

    Slartibartfast's explanation that notifyDataSetChanged() only works when add, insert,remove, or clear is called on the adapter is incorrect.

    That explanation is true of the setNotifyOnChange() method, which if set to true (as it is by default) will automatically call notifyDataSetChanged() when any of those four actions occur.

    I think the poster confused the two methods. notifyDatasetChanged() itself does not have those restrictions. It just tells the adapter that the list it is looking at has changed, and it does not matter how the change to the list actually happened.

    While I can't see the source code for your createNewDeviceList(), I would guess your problem came from the fact that you had the adapter referencing the original list you created, and then you created a new list in createNewDeviceList(), and since the adapter was still pointing to the old list it could not see the changes.

    The solution slartibartfast mentioned works because it clears the adapter and specifically adds the updated list to that adapter. Thus you don't have the problem of your adapter pointing to the wrong place.

    Hope this helps someone!

提交回复
热议问题