1

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(....));?

Community
  • 1
  • 1
Anonymous
  • 4,470
  • 3
  • 36
  • 67

2 Answers2

3

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).

matiash
  • 54,791
  • 16
  • 125
  • 154
  • Another important difference is that you'll also lose the ability to use stable id's to maintain your scroll position... The ListView won't know if the stable id's for the new adapter are the same as the old adapter and it will send your user back to the top of the list. – sddamico Jun 09 '14 at 15:34
  • So (apart from the scrolling at top point) there is difference only when I'm using a ViewHolder in the getView() method to re-use views? – Anonymous Jun 09 '14 at 15:41
  • The difference is actually weteher you use the supplied `convertView` or not (i.e. always ignore its value and create/inflate a new view). The ViewHolder pattern is just a further optimization on this. Edited answer to include this point. – matiash Jun 09 '14 at 15:44
1

setAdapter() will clear the scrap heap which is used to save as convertView,and it will also set a new adapter,then it will requestLayout().

However,notifyDataSetChanged() just requestLayout().So the scrap heap is still there,and when getView() happens,the convertView will not be null if scrap heap contains it,so it need not to be inflated.

So,when data changed,it's more efficient to call notifyDataSetChanged() but not setAdapter().

Francis Shi
  • 395
  • 4
  • 8