'kotlin.TypeCastException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment at NavigationExtensionsKt

I copied the NavigationExtensions.kt extension file from the NavigationAdvancedSample and I get this exception:
Solution 1:[1]
UPDATE: make sure your menu item ids are the same as your navigation resource files ids
also: if you're having a problem with ItemReselectedListener Add null safety checks, your listener should be something like this:
setOnNavigationItemReselectedListener { item ->
val newlySelectedItemTag = graphIdToTagMap[item.itemId]
val selectedFragment = fragmentManager.findFragmentByTag(newlySelectedItemTag)
as NavHostFragment?
val navController = selectedFragment?.navController
// Pop the back stack to the start destination of the current navController graph
navController?.popBackStack(
navController.graph.startDestination, false
)
}
Solution 2:[2]
In my case, I forgot to add android:name="androidx.navigation.fragment.NavHostFragment" in FragmentContainerView
Solution 3:[3]
I also faced this probelem, the solution is actually very simple.
Make sure your menu item's id match the id of NAV_GRAPH not destinations.
I was using the same ids for menu items and destinations, but in this case, menu item should have same id as of NAV_GRAPH.
Solution 4:[4]
I also had the same issue
Check that you have set your start destination and attached it to a fragment. in your nav graph set app:startDestination="@id/your fragment"
this should solve your problem
Solution 5:[5]
I manage to solve this problem.
In my case, I was calling val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment before setContentView(binding.root) so I change the order of the methods and everything was Ok.
Solution 6:[6]
can you try with this?
val selectedFragment: NavHostFragment? = fragmentManager.findFragmentByTag(newlySelectedItemTag) as NavHostFragment
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Harshal Pudale |
| Solution 3 | |
| Solution 4 | Andrew Ananda |
| Solution 5 | Desilio do Carmo Lima Neto |
| Solution 6 | Dimitar |
