1

The situation: Upon receiving an SMS, the MyReceiver class extracts the SMS and should then use a ViewModel object to insert data into a database. The documentation focuses on instantiation from a class extending AppCompatActivity, but is it necessary to pass an existing activity's ownership to the ViewModelProvider constructor?

The problem: Getting access to a ViewModel Object from a public class (not an activity).

public class MyReceiver extends BroadcastReceiver{
   public void onReceive(Context context, Intent intent){
      mMyViewModel = new ViewModelProvider(??).get(MyViewModel.class);
   }
}

Attempted solutions: In order to pass this to the ViewModelProvider constructor I tried to make MyReceiver implement androidx.lifecycle.ViewModelStoreOwner. This requires overriding the method getViewModelStore. But I do not understand what a ViewModelStore is or how to create it to return a ViewModel.

@NonNull
@Override
public ViewModelStore getViewModelStore(){
   return ??; 
}

Any help would be greatly appreciated.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • Does this answer your question? [The correct way to obtain a ViewModel instance outside of an Activity or a Fragment](https://stackoverflow.com/questions/51007271/the-correct-way-to-obtain-a-viewmodel-instance-outside-of-an-activity-or-a-fragm) – Abhinav Suman Apr 01 '20 at 08:59
  • it absolutely does, thank you – Matteo Kalogirou Apr 02 '20 at 09:03

1 Answers1

0

Your problem similiar to this question The correct way to obtain a ViewModel instance outside of an Activity or a Fragment

You shouldn't instantiate the viewmodel in non activity/fragment class. In your case, when onReceive triggered you should "inform" the activity/fragment then do your action on that activity/fragment. so the instantiation of viewmodel should be done on your activity/fragment.

Pasca
  • 36
  • 5