Home > front end >  BottomNavigationView throws NullPointerException
BottomNavigationView throws NullPointerException

Time:05-03

Hello im trying to implement BottomNavigationView with Navigation component.. I used the official doc as a reference while building it.. but when I run the project I get a java.lang.NullPointerException... I can't seem to figure out what I did wrong

This is my MainActivity:

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private lateinit var navController: NavController


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

        setUpBottomNavigationBar()

    }

    private fun setUpBottomNavigationBar() {
        val navHostFragment = supportFragmentManager.findFragmentById(
            R.id.fragment_container
        ) as NavHostFragment
        navController = navHostFragment.navController

        // Setup the bottom navigation view with navController
        val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_navigation_view)
        bottomNavigationView.setupWithNavController(navController)
    }

}

MainActivity layout res file:

 <fragment
        android:id="@ id/fragment_container"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_navigation_view"/>


    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@ id/bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bottom_navigation_menu" /> 

error:

2022-05-02 14:28:58.746 5952-5952/com.example.dogexplorer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.dogexplorer, PID: 5952
    java.lang.NullPointerException
        at androidx.navigation.ui.NavigationUI.onNavDestinationSelected(NavigationUI.kt:69)
        at androidx.navigation.ui.NavigationUI.setupWithNavController$lambda-6(NavigationUI.kt:602)
        at androidx.navigation.ui.NavigationUI.$r8$lambda$6wzEv9QqEZKdQFS1sQQy-bdQvgE(NavigationUI.kt)
        at androidx.navigation.ui.NavigationUI$$ExternalSyntheticLambda2.onNavigationItemSelected(D8$$SyntheticClass) .......

CodePudding user response:

You need to add nav graph at your fragment_container, for creating a nav graph right click on res folder -> new android resource file -> type: navigation

app:navGraph="@navigation/your_navigation_graph"

documentation -> https://developer.android.com/guide/navigation/navigation-getting-started

  • Related