0

I have a Timer that sends a notification when the timer is done. Clicking this notification restarts the activity, deleting all the timer information. For this reason, I decided to use saved State for View Model.

 class TimerViewModel(val savedStateHandle: SavedStateHandle) : ViewModel() {

    val savedBundleTimerState : MutableLiveData<TimerState> = savedStateHandle.getLiveData(
        TIMER_STATE, timerState.value) 
//rest of code

Then I'm getting a reference in the fragment:

class FragmentTimer : Fragment() {

lateinit var timerViewModel: TimerViewModel

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.fragment_timer,
        container,
        false
    )

    //reference to timerViewModel, using SavedState
    val application = requireActivity().application
    timerViewModel= ViewModelProvider(this,
        SavedStateViewModelFactory(application, this)).get(TimerViewModel::class.java)

But when I run the app I get the error

2022-02-05 15:04:01.945 8460-8460/com.example.pomodorotechnique E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.pomodorotechnique, PID: 8460 java.lang.RuntimeException: An exception happened in constructor of class com.example.pomodorotechnique.TimerViewModel

I've searching how to define the SavedStateRegistryOwner and I run into this question, which is very illustrating, but still doesn't work when I run the app

Any suggestions will be much appreciated!

  • It'll tell you why construction is failing further down the stacktrace, you just posted the first line. Referencing ``timerState.value`` is suspicious (is it valid? is it null?) but without seeing the full code it's just a guess. Also fyi you can just do ``val timerViewModel: TimerViewModel by activityViewModels()`` without needing to mess with factories and activity/application references – cactustictacs Apr 22 '22 at 18:37
  • Thank you so much! That definitely solved it! – Ariel Di Pietro Apr 22 '22 at 19:27

0 Answers0