Case is of Activity-Fragment Recreate : I am creating ViewModel from activity context at activity level and trying to access the initialised ViewModel at Fragment level, using ViewModelProvider.of().
Below code works in happy case; but when activity is recreated (changes system language or permission), same code don't work, and fragment is not able to access the activity created viewModel.
ViewModel is parameterised and has only one primary constructor and initialised using ViewModelProvider.Factory
class MessageViewModel(var message: MutableLiveData<String>): ViewModel() { ... }
val viewModel = ViewModelProviders.of(this, MessageVMFactory())
.get(MessageViewModel::class.java)
val viewModel = ViewModelProviders.of(activity)
.get(MessageViewModel::class.java)
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.krp.android.viewmodeldemo/com.krp.android.viewmodeldemo.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.krp.android.viewmodeldemo.utility.MessageViewModel
If you have initialised the ViewModel via Factory, you must access it via Factory, regardless of any context. Seems ViewModel issue when system recreates activity or fragment.
It works fine at Fragment when
val viewModel = ViewModelProviders.of(activity, MessageVMFactory())
.get(MessageViewModel::class.java)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With