Search code examples
androidbroadcastreceiverandroid-viewmodel

How to access MyViewModel(AndroidViewModel) in Broadcast Receiver


I recently implemented Room in my android app. (https://developer.android.com/training/data-storage/room)

It works well in 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);
            }
        }
    });

However I can't use the Room in my BroadcastReciever

mWritedSMSViewModel = new ViewModelProvider(???).get(WritedSMSViewModel.class);

The problem is I don't know what argument should be used above code. I confirmed that this and context cannot be used as the parameter.

What's wrong with me?


Solution

  • You shouldn't do that. It's bad practice. Because ViewModels only attached with Activity and Fragment Only.

    One thing possible to achieve your requirements.

    Separate your Room DB operation from ViewModel in a separate singleton class. Use it in ViewModel and any other place required. When Broadcast is received, write data to DB through this singleton class rather than ViewModel.

    If you are observing for the LiveData in your Fragment, then it will update your views too.