Search code examples
androidandroid-listviewlistview-adapter

Android ListView - difference between adapter.notifyDataSetChanged and using new adapter


My question is based on this post.

Android. How does notifyDataSetChanged() method and ListViews work?

I've read in various articles that to refresh the listView you must call notifyDataSetChanged() and not listView.setAdapter(new Adapter(....)); because the second method is too costly and affects performance

The answer to the above question says that adapter.notifyDataSetChanged() affects the views that are currently visible on the screen. So getView() is called as many times as the number of items currently displayed.

But getView() is called the same number of times when assigning a new adapter to the listView as well.

So what is the difference between calling adapter.notifyDataSetChanged() and listView.setAdapter(new Adapter(....));?


Solution

  • When you call notifyDataSetChanged(), getView() is called the same number of times. However, since the adapter is the same, these views can be reused (i.e. passed as convertView).

    That cannot be done when supplying a new adapter, because the ListView cannot know for sure that the new adapter uses the same layouts. So the recycler is cleared, and all rows must be created from scratch (which is far costlier than reusing them).

    (This performance point is moot if you ignore the supplied convertView and always create/inflate a new view -- but that's a bad idea anyway).