I am attempting to set a navHostFragment in my MainActivity.kt file, but the code below results in the error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lunchtray/com.example.lunchtray.MainActivity}: java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment
class MainActivity : AppCompatActivity() {
private lateinit var navController: NavController
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val navHostFragment = supportFragmentManager // NULL CANNOT BE CAST TO NON NULL TYPE
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
setupActionBarWithNavController(navController)
}
override fun onSupportNavigateUp(): Boolean {
return navController.navigateUp() || super.onSupportNavigateUp()
}
}
activity_main.xml layout file:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@ id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
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:navGraph="@navigation/mobile_navigation"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
What am I doing wrong? Similar questions exist on SO but they involve using menu IDs or initializing the navHostFragment from within a fragment, this is a much more straightforward situation and I do not understand why any value should be null.
CodePudding user response:
You forgot to call setContentView(R.layout.activity_main)
, which means you have no FragmentContainerView
and no fragment within it, hence why findFragmentById(R.id.nav_host_fragment)
returns null.
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
As an alternative, you can also call the AppCompatActivity construct that takes a LayoutRes
, which will automatically call setContentView
for you as part of super.onCreate()
:
class MainActivity : AppCompatActivity(R.ayout.activity_main) {