architecture-components-samples: TypeCastException in NavigationExtensions.kt

Hello

I am working on a hobby app, using bottom navigation bar. I copied the NavigationExtensions.kt extension file from the NavigationAdvancedSample and I get this exception:

kotlin.TypeCastException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment at com.sanislo.soft.photospot.NavigationExtensionsKt$setupItemReselected$1.onNavigationItemReselected(NavigationExtensions.kt:187) at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:201) at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840) at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158) at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991) at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:115) at android.view.View.performClick(View.java:7352) at android.view.View.performClickInternal(View.java:7318) at android.view.View.access$3200(View.java:846) at android.view.View$PerformClick.run(View.java:27800) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7037) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

About this issue

Most upvoted comments

So I figured out that the reason why I was getting this exception because the navigation graphs id in the xml should match the id of the menu items in the bottom navigation menu xml.

I think there should be a red huge warning about this restriction, because I have lost like 5 hours of my life debugging this error…

I had a similar problem, after several hours a discover that I forget to pass the layout as the activity parameter: AppCompatActivity(R.layout.activity_main)

@DanielMarantz I created a separate test project from scratch, just to see what did I do wrong, and that’s how I noticed the mistake.