javaandroidandroid-studioandroid-fragmentsandroid-navigation-bar

ERROR: cannot be cast to androidx.navigation.fragment.NavHostFragment. -- app crashing every time


So I'm trying to build an app with a bottom navigation bar that will switch between fragments. I did the coding according to some documentation.

I tried every solution on the internet but none of them seems to work for me.

the error:

Caused by: java.lang.ClassCastException: com.example.jetpacklesson.MainFragment cannot be cast to androidx.navigation.fragment.NavHostFragment
        at com.example.jetpacklesson.MainActivity.onCreate(MainActivity.java:30)

here is the XML main activity code

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/firstFragmentHolder"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:name="com.example.jetpacklesson.MainFragment"
        app:defaultNavHost = "true"
        app:layout_constraintBottom_toTopOf="@+id/bnv_bottomBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph = "@navigation/nav_graph"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bnv_bottomBar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/nav_bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

and main activity java code:


    BottomNavigationView bnv_navigationBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.firstFragmentHolder);
        NavController navController = navHostFragment.getNavController();
        bnv_navigationBar = findViewById(R.id.bnv_bottomBar);
        NavigationUI.setupWithNavController(bnv_navigationBar, navController);
    }

Solution

  • Your XML file says:

    android:name="com.example.jetpacklesson.MainFragment"
    

    If you want that to be a NavHostFragment, you need to change that to

    android:name="androidx.navigation.fragment.NavHostFragment"
    

    As per the Navigation Getting Started guide.