我最近在我的 android 应用程序中实现了 Room。(https://developer.android.com/training/data-storage/room)
它在Activities
.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWritedSMSViewModel = new ViewModelProvider(this).get(WritedSMSViewModel.class);
mWritedSMSViewModel.getAllWritedSMSs().observe(this, new Observer<List<WritedSMS>>() {
@Override
public void onChanged(@Nullable final List<WritedSMS> smss) {
// Update the cached copy of the words in the adapter.
if(smss != null) {
mAdapter.setSMSs(smss);
}
}
});
但是我不能使用我的房间 BroadcastReciever
mWritedSMSViewModel = new ViewModelProvider(???).get(WritedSMSViewModel.class);
问题是我不知道上面的代码应该使用什么参数。我确认了this
,context
不能用作参数。
我怎么了?
你不应该那样做。这是不好的做法。因为 ViewModels 只附加了
Activity
andFragment
Only。
一件事可以实现您的要求。
将您的Room DB
操作与ViewModel
单独的singleton
类分开。在ViewModel
任何其他需要的地方使用它。当Broadcast
被接收时,写数据到DB通过这个单例类,而不是视图模型。
如果您正在观察LiveData
中的Fragment
,那么它也会更新您的视图。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句