Changing start destination doesn't cancel the previous start destination in nav controller Android Navigation-ThrowExceptions

Exception or error:

I am trying to change the start destination in my graph programmatically. When my flag is set to true the start destination (R.id.mainMenuFragment) is assigned in onCreate correctly and displayed as expected but in a sec (seems after onCreate) another start destination (R.id.laneBootFragmen) kicks in from the graph so it seems 2 destinations (or 2 graphs??) are applied.

here is the set up.

The graph R.navigation.app_navigation:

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/mobile_navigation"
    app:startDestination="@id/bootFragment">

    <fragment
        android:id="@+id/bootFragment"
        android:name="com.test.ui.view.BootFragment"
        android:label="MainMenuFragment" />

    <fragment
        android:id="@+id/mainMenuFragment"
        android:name="com.test.ui.mainmenu.view.MainMenuFragment"
        android:label="MainMenuFragment" />

The MainActivity xml:

 <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

The code where I set the start destination programmatically:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.includeDevicePasswordPrompt.viewModel = mViewModel

        checkIfAppIsRestartedAfterCrash()
    }

    private fun checkIfAppIsRestartedAfterCrash() {
        val controller =
            findNavController(R.id.nav_host_fragment)
        controller.navInflater
            .inflate(R.navigation.app_navigation).let {
                if (intent.extras?.getBoolean(APP_RESTARTED_AFTER_CRASH) == true) {
                    it.startDestination = R.id.mainMenuFragment
                } else {
                    it.startDestination = R.id.bootFragment
                }
                controller.graph = it
            }
        intent.removeExtra(APP_RESTARTED_AFTER_CRASH)
    }

The goal is to have startDestination assigned as expected programmatically

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *