Android: notifyDataSetChanged(); not working
It might be worth checking if you have an empty override for registerDataSetObserver()
. Android Studio added one for me without implementing the call to super. Adding it in as follows was enough to get my listView working again:
@Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
}
The thing you need to edit is put your
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_NSERIE,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA},
new int[] { R.id.id, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria});
setListAdapter(adapter);
adapter.notifyDataSetChanged();
// timer();
}
});
into the OnCreate(). and return the list candidatosList from Asynctask. than set timer for updating candidatosList list.
One of the main reasons notifyDataSetChanged()
won't work for you - is,
Your adapter loses reference to your list.
When you first initialize the Adapter
it takes a reference of your arrayList
and passes it to its superclass. But if you reinitialize your existing arrayList
it loses the reference, and hence, the communication channel with Adapter
.
When creating and adding a new list to the Adapter
. Always follow these guidelines:
- Initialise the
arrayList
while declaring it globally. - Add the List to the adapter directly without checking for null and empty values. Set the adapter to the list directly (don't check for any condition). Adapter guarantees you that wherever you make changes to the data of the
arrayList
it will take care of it, but never lose the reference. - Always modify the data in the arrayList itself (if your data is completely new then you can call
adapter.clear()
andarrayList.clear()
before actually adding data to the list) but don't set the adapter i.e If the new data is populated in thearrayList
than justadapter.notifyDataSetChanged()
Stay true to the Documentation.