Search code examples
androidandroid-dialogfragmentandroid-architecture-components

Android DialogFragment Navigation Crash/Issue


I have a dialog navigation graph that works fine if I dont dismiss dialogs while navigating to another. But then, the dialog I navigate from doesnt disappear from the screen. If i dismiss them while navigating the app crashes.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val navHostFragment = activity?.supportFragmentManager?.findFragmentById(R.id.dialogNavigation) as NavHostFragment
        val navController = navHostFragment.navController
        super.onViewCreated(view, savedInstanceState)
        binding.btnNext.setOnClickListener{
            navController.navigate(R.id.action_retryConnectionDialog_to_batteryDialog)
            dismiss()
        }
    }

This is the part of the code (within RetryConnectionDialog.kt) that produces such reactions, any insight would be appreciated


Solution

  • If you want to dismiss your dialog when moving to your new destination, you must do that as part of your navigate() action by using popUpTo on your action_retryConnectionDialog_to_batteryDialog - dismiss is an asynchronous operation that happens only after your navigate() call happens, which means it is too late to remove it from the back stack (as your new BatteryDialog is already stacked on top of it).

        <action
            android:id="@+id/action_retryConnectionDialog_to_batteryDialog"
            app:destination="@id/batteryDialog"
            app:popUpTo="@+id/retryConnectionDialog"
            app:popUpToInclusive="true"/>