0

My activity code:

class MyActivity : AppCompatActivity(){
 private val viewModel : SharedViewModel by viewModels()
//***
//***
//***
}

My fragment code:

class MyFragment : Fragment(){
 private val viewModel : SharedViewModel by activityViewModels()
//***
//***
//***
}

When I create the ViewModel within the activity only then everything works fine. But when I try to create it also in the activity's fragment then I have the error:

Caused by: android.view.InflateException: (...) Error inflating class fragment
SharedFragment.getViewModel(SharedFragment.kt:23)
SharedFragment.onViewCreated(SharedFragment.kt:23)
Caused by: java.lang.IllegalArgumentException: CreationExtras must have a value by `SAVED_STATE_REGISTRY_OWNER_KEY`
MyActivity.onCreate(MyActivity.kt:60)
  • Does this answer your question? [CreationExtras must have a value by \`SAVED\_STATE\_REGISTRY\_OWNER\_KEY\`](https://stackoverflow.com/questions/73302605/creationextras-must-have-a-value-by-saved-state-registry-owner-key) – denvercoder9 Oct 24 '22 at 18:19
  • This should help https://stackoverflow.com/questions/60885459/how-to-share-data-between-activity-and-fragment-via-viewmodel-class-in-android – KittenLS Oct 24 '22 at 18:57
  • Yes, adding the "implementation "androidx.fragment:fragment-ktx:1.5.2" has solved the problem. – GrimPloughman Oct 27 '22 at 09:27

0 Answers0