Hello, question about restoring the nav graph when...
# navigation-architecture-component
v
Hello, question about restoring the nav graph when the activity is recreated from a configuration change and the nav graph has been defined using the Kotlin DSL API. The fragment restoration process seems to crash with the
IllegalStateException: You must call setGraph() before calling getGraph()
since the fragment is trying to access route specific parameters on its
onCreate
method. I located the issue here: https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-naviga[…]ain/java/androidx/navigation/fragment/NavHostFragment.kt How should the system restore the graph if its not defined in XML and therefore doesn't have a graph ID? I also cannot manually set the graph myself since the
NavHostFragment
is inflated in the
FragmentContainerView
in the main activity's layout XML and I do not have access to it before the whole
onCreate
stack has completed and
setContentView
is called in the main activity.
Im using 2.8.9 but it has the same block of code thats handling the graph restoration
For anyone else wondering about this, one solution I found was to subclass the
NavHostFragment
and override the
onCreate
method such as such:
Copy code
override fun onCreate(savedInstanceState: Bundle?) {
        // Initializes the parent class navHostController
        navController
        // Sets the graph after the above init has restored the back stack
        navController.graph = navController.createGraph(...) { ... }
        // Finally call the super.onCreate to complete the init process
        super.onCreate(savedInstanceState)
}