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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With