Search code examples
androidandroid-recyclerviewnotifydatasetchanged

Notify dataset changed not fetching new data for the recyclerview


I have a recyclerview that is not updating and I am not sure why:

In my main fragment I get the data for the my recyclerview in oncreateview like this:

    alarms = AlarmCollection.getAlarms(getActivity());

and then I set the adapter like this:

    // Adapter
    adapter = new AlarmsAdapter(getActivity(), alarms);
    rv.setAdapter(adapter);

And then I reset the data on a timertask/runnable to update the values of on the recyclerview (they are alarms so they change once a minute).

This is done through a simple notify datasetchanged:

adapter.notifyDataSetChanged();

The problem is though as you can see above I load the data through AlarmCollection. This is grabbing the list from the shared preferences.

But when I am calling notify dataset changed this is not being called again.

I was under the impression that when you call notify ect on a recyclerview it would update the list or does it pureley update the view?


Solution

  • As @GpRyan mentioned, the problem lies in this line :

    alarms = AlarmCollection.getAlarms(getActivity());
    

    Every time you make a new instance of alarms.But the adapter is looking for changes in the instance of alarms you passed to it. so it won't work.

    what you should do is removing all items from alarms and add your new data again.

    alarms.removeAll();
    alarms.addAll(AlarmCollection.getAlarms(getActivity()));
    adapter.notifyDataSetChanged();
    

    NOTE: Update the alarmsin your main thread. Once, it takes me a long time that i understand updating the data set in another thread wont work with adapter.