Added a little more info of how some things can fit together to JaviMar's answer in Kotlin:
class RoomWidgetService : RemoteViewsService() {
override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
return RoomRemoteViewsFactory(this.applicationContext, intent)
}
}
class RoomRemoteViewsFactory(private val context: Context, intent: Intent) : RemoteViewsService.RemoteViewsFactory {
private var todos: List<TodoItem> = listOf()
private lateinit var todoDao: TodoDao
override fun onCreate() {
val database = TodoRoomDatabase.getDatabase(context)
todoDao = database.todoDao()
}
override fun onDataSetChanged() {
todos = todoDao.getTodosSync()
}
// rest of class...
}
I notify the widget of an update by observing something. You could observe the ViewModel in the main activity, or the Application. Not sure the best place to observe the data.
todoViewModel.todoItems.observe(this) {
val appWidgetManager = AppWidgetManager.getInstance(applicationContext)
val thisAppWidget = ComponentName(
applicationContext.packageName,
RoomWidget::class.java.name
)
val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget)
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_view )
}
notifyAppWidgetViewDataChanged()
should be called? If it should be called within the ViewModel class, how are references to widgetIds retreived? – Haematoma