AndroidViewModel instantiated without passing application context?

后端 未结 2 1067
时光说笑
时光说笑 2021-01-13 13:35

I am currently digging through the Android Room with a View sample app, full source code available here. In this project, an WordViewModel of type Android

2条回答
  •  庸人自扰
    2021-01-13 14:23

    AndroidX-Activity 1.2.0's ComponentActivity (and therefore AppCompatActivity) implements HasDefaultViewModelProviderFactory, which returns an ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication()) from your Activity/Fragment by default, allowing you to get the application from this AndroidViewModelFactory without you having to explicitly pass it.

    Then, this factory instantiates your ViewModel via reflection using a __(application) constructor.

    It's generally a better idea to use SavedStateViewModelFactory in order to be able to receive a SavedStateHandle in a similar manner (___(application, savedStateHandle)) though.

    So to fix the problem, you need to add up-to-date versions of core-ktx, activity-ktx and fragment-ktx explicitly in your code.

提交回复
热议问题