android / architecture-components-samples

Samples for Android Architecture Components.
https://d.android.com/arch
Apache License 2.0
23.4k stars 8.29k forks source link

NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment #979

Open GrishinSergey opened 3 years ago

GrishinSergey commented 3 years ago

I'm using helper extension from NavigationAdvancedSample for BottomNavigationView, and it works well, when I just set menu at the start of application. In my logic I need to reset BottomNavigationView's items in runtime depends on API's result, so I'm reseting it like this:

bottomNavigationView.menu.clear()
bottomNavigationView.inflateMenu(R.menu.navigation)
val featuresToRemove = UiBottomNavigationMenuItem.values() - bottomNavFeatures
featuresToRemove.forEach { bottomNavigationView.menu.removeItem(it.bottomMenuItemId) }

Also I'm reseting this extension like this:

val navControllerLiveData = bottomNavigationView.setupWithNavController(
    navGraphIds = /* list with new navGraphIds */,
    fragmentManager = supportFragmentManager,
    containerId = R.id.container,
    intent = intent
)

The problem is that when I click on bottom nav menu item, It crashes in this extension:

setOnNavigationItemSelectedListener { item ->
    // Don't do anything if the state is state has already been saved.
    if (fragmentManager.isStateSaved) {
        false
    } else {
        val newlySelectedItemTag = graphIdToTagMap[item.itemId]
        if (selectedItemTag != newlySelectedItemTag) {
            // Pop everything above the first fragment (the "fixed start destination")
            fragmentManager.popBackStack(firstFragmentTag, FragmentManager.POP_BACK_STACK_INCLUSIVE)

            /*
             * Crash appears in this line. fragmentManager doesn't find fragment for show the tab 
             */
            val selectedFragment = fragmentManager.findFragmentByTag(newlySelectedItemTag) as NavHostFragment

            // another part of extension ...
            true
        } else {
            false
        }
    }
}

I've tried to research issues and found one #693 but my case is not the same - I've checked, and my ids is the same - in graph and in bottom nav menu xml. So I guess that the problem is in FragmentManager or extension.

Also I tried clear fragment manager from old fragments before reset bottom bar and extension:

val transaction = supportFragmentManager.beginTransaction()
// 0..5 -- indices of items in BottomNavigationView
(0..5).map(::getFragmentTag).forEach { fragmentTagToRemove ->
    supportFragmentManager.findFragmentByTag(fragmentTagToRemove)?.let(transaction::remove)
}
transaction.commit()