Search code examples
androidandroid-fragmentsbroadcastreceiverandroid-roomandroid-viewmodel

Accessing data made by ViewModel in a broadcastReceiver


I want to be able to access the alarms that i have set through the AlarmViewModel, as they need to be remade on boot. I however cannot seem to figure out how i can get access to the same repository (I do all db access through the repository).

In my OnReceive(Context context, Intent intent) i have:

public void onReceive(Context context, Intent intent) {
        if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
            AlarmRepository alarmRepository = new AlarmRepository((Application)context.getApplicationContext());
 }
}

The constructor of the view model is this:

public AlarmViewModel(Application application){
        super(application);
        repository = new AlarmRepository(application);
        allAlarms = repository.getAlarms();
    }

My fragment get the viewmodel by:

alarmViewModel = ViewModelProviders.of(requireActivity()).get(AlarmViewModel.class);

My project follows this overall db architechture - it's just based on a single activity and fragments instead. https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0


Solution

  • The error was actually not that i did not get the right alarmRepository, but rather that a LiveData object is only filled lazily, hence it was null until i added a listener.