Search code examples
androidfragmentlistadapter

Updating FragmentList adapter bassed on data in SQlite database, when the underlying data changes


I have an android application (running under support library) which have MyListFragment class extends ListFragment. Here is code for create ListAdapter:

public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);      
   DbHelperEvent dbHelper = new DbHelperEvent(getActivity());
   ArrayList<ReportEvent> events = new ArrayList<ReportEvent>();
   events = dbHelper.getAllEvents();
   dbHelper.close();

   this.adapterAllEvents = new ArrayAdapter<ReportEvent>(getActivity(), android.R.layout.simple_spinner_item, events);
   this.adapterAllEvents.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
   setListAdapter(adapterAllEvents);}

But underlying data can change anytime, and I need to detect this change and update ListAdapter. But i don't have any idea what should i use to detect these changes.


Solution

  • It depends:

    • if your DB is always the same and you only have to detect changes in adapterAllEvents, call notifyDataSetChanged() on adaper

    • if your data is changing in DB, you can use CursorLoader and LoaderManager.LoaderCallbacks to obtain the Cursor object to pass to CursorAdapter. Call restartLoader when your data changes