1

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?

0 Answers0