Pass params from fragment to ViewModel

I use SavedStateHandle to pass data between different components. My fragment use SavedStateViewModelFactory to initialize my VM (is it correct the initalization?) and a method in companion object to update the savedState.

My dependencies:

implementation "androidx.activity:activity-ktx:1.1.0"
implementation "androidx.fragment:fragment-ktx:1.2.4"
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:2.2.0"

The ViewModel initalization in Fragment:

private val viewModel: MyViewModel by viewModels {
        SavedStateViewModelFactory(activity?.applicationContext as Application, this)
}

Is it a good way to initialize ViewModel?

When I want to update my saved values I use this method:

companion object {

    @JvmStatic
    fun newInstance(cod: String, password: String) =
        MyFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_COD, cod)
                putString(ARG_PASSWORD, password)
            }
        }
}

After called newInstance (that should update saved state), I run the method printCod in my ViewModel.
This is the VM:

class MyViewModel(
    private val state: SavedStateHandle
    ) : ViewModel(){

    fun getCurrentCod(): String {
        return state.get(ARG_COD)?: ""
    }

    fun printCod() {
        println(getCurrentCod())
    }

    companion object {
        private val ARG_COD = "cod"
        private val ARG_PASSWORD = "password"
    }
}

My “main” (where code above is executed):

newInstance(userCode, userPass)
viewModel.printCod()

I spent two days understanding why printCod print always an empty string. would someone know how to help me by giving me advice or at least tell me where am i wrong?

Your newInstance() function is setting the fragment’s argument bundle, which has nothing to do with the view model’s saved state handle. When you want to update the view model’s saved state, the view model should call state.set(key, value).

Also, SavedStateHandle is not used for passing data from a fragment to a view model. It is a place for the view model to remember things, so it can restore the data after your process is killed and restarted.

If you need to pass data from the UI (e.g. a fragment) to the view model, have the UI call a method or set a property on the view model.

Thanks for your answer. Ok that’s clearer but when my activity destroy and then re-create, it doesn’t restore data from the savedInstancestate.

In onCreate:

arguments?.let {
        cod= it.getString(ARG_COD)
        password= it.getString(ARG_PASSWORD)
    }

Arguments is always null and the fragment never restore data from savedInstanceState. Do you know why? Thanks!