Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to access Room database from widget

i wanted to access Room DB inside my widget class to update the widget according to the stored data.

the problem here is the ViewModelProvider require a fragment or activity to work with..

ViewModelProviders.of(fragment).get(YourViewModel.class);

which is not available in the app widget class so how to do it?

like image 574
Amr Ahmed Avatar asked Aug 22 '18 19:08

Amr Ahmed


1 Answers

If you use a RemoteViewsService to populate your widget UI, then you can avoid using an AsyncTask by including a DAO query in its onDataSetChanged() method, rather than in the AppWidgetProvider's onUpdate() method. As stated in the onDataSetChanged() documentation,

...expensive tasks can be safely performed synchronously within this method. In the interim, the old data will be displayed within the widget.

The other advantage here is that you can include a call to AppWidgetManager.notifyAppWidgetViewDataChanged() in your app's ViewModel observer's onChanged() method; this will trigger the onDataSetChanged() and the widget will update each time the Room database is changed, rather than just at the fixed interval for onUpdate().

like image 82
Aaron Dunigan AtLee Avatar answered Oct 10 '22 18:10

Aaron Dunigan AtLee