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!