I have an single activity application with jetpack navigation, I need an object variable for all my application in many fragments. So I use a ViewModel, and I've created a Parent Fragment class which provide the ViewModel :
class MyViewModel : ViewModel() {
var myData : CustomClass? = null
...
}
open class ParentFragment : Fragment {
val model : MyViewModel by activityViewModels()
lateinit var myData : CustomClass
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.myData?.let {
myData = it
}
}
}
myDatashould not be null where I use ParentFragment, but sometimes, randomly I get kotlin.UninitializedPropertyAccessException: lateinit property myData has not been initialized when I use myData
Is it possible that my ViewModel doesn't keep myData? How can I be sure that my property has been initialized ?
UPDATE : Try 1
I've tried this code in my ParentFragment:
open class ParentFragment : Fragment {
val model : MyViewModel by activityViewModels()
lateinit var backingData : CustomClass
val myData : CustomClass
get() {
if (!::backingData.isInitialized)
model.getData()?.let {
backingData = it
}
return backingData
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.getData?.let {
backingData = it
}
}
}
But the problem doesn't disappear when I call myData, it seem's the ViewModelloses my data
UPDATE 2 : More code details
Before to go inside a fragment which extends ParentFragment, I set my data in ViewModel and then I navigate to the next fragment as below :
// Inside FirstFragment
if (myData != null) {
model.setData(myData)
findNavController().navigate(FirstFragmentDirections.actionFirstToNextFragment())
}
Is it possible that my NavController does navigation before the data was setted ?
EDIT 3 : Try to use custom Application class
According to an answer below, I've implemented a custom Application class, and I've tried to pass my object through this class :
class MyApplication: Application() {
companion object {
var myObject: CustomClass? = null
}
}
But unfortunately, there is no change for me. Maybe my object is too big to allocate correctly ?