SoFunction
Updated on 2025-03-11

Android failed to call notifyDataSetChanged method

Android failed to call notifyDataSetChanged method

If you use ListView, GridView, etc. for data display, when the bound data is updated, the ListView needs to be refreshed in real time, that is, the notifyDataSetChanged method of Adapter is called. However, many people will find that the ListView is not refreshed after calling. What is the reason? It will be explained in detail below.

1. The data source has not been updated, and calling notifyDataSetChanged is invalid.
2. The data source has been updated, but it points to a new reference. Calling notifyDataSetChanged is invalid.
3. The data source has been updated, but adpter has not received a message notification and cannot update the list dynamically.

A typical error is:

list = new String[]{"listView item"};
adapter = new ArrayAdapter<String>(this,.simple_list_item_1,list);
(adapter);
list = new String[]{"new listView item"};
();

I used to think that the adapter would listen to the changes in the list. After the list is re-initialized, the ListView will automatically refresh the data. In fact, it is not the case. The adapter listens to the changes in new String[]{"listView item"}. The adapter itself will hold an internal reference to the original data source (new String[]{"listView item"}).

After executing the list = new String[]{"new listView1 item"}; statement, the list is reinitialized, which is equivalent to cutting off the relationship between the list and the original data source (new String[]{"listView item"}). Therefore, calling notifyDataSetChanged will not work, because list and inner_list are already two completely different objects that exist on the heap.

Error review:

It was some time agoArrayist and other uses as original data sources generally perform operations such as add, so list and inner_list have always kept references to the same variable, and there was no problem. Of course, if you change to direct assignment, the call will be invalid.So you need to operate on the original data object instead of reassigning the value.

I took a look at the source code of Arrayadapter:

ArrayAdapter:
public ArrayAdapter(Context context, int textViewResourceId, T[] objects) {
  init(context, textViewResourceId, 0, (objects));
}
Arrays:
public static &lt;T&gt; List&lt;T&gt; asList(T... array) {
  return new ArrayList&lt;T&gt;(array);//Note that the ArrayList here is not the common ArrayList, but an internal class of Arrays.  .}


The above is a summary of the common reasons and solutions for the failure of Android calling notifyDataSetChanged method. If you have any questions, I hope you will leave a message to discuss, or go to this website community for your discussion. Thank you for reading. I hope it can help you. Thank you for your support for this website!