exception: View does not have a navController set

james rm picture james rm · Aug 27, 2019 · Viewed 9.6k times · Source

in the fragment which i made it host in the tag fragment in activity when i use navController = Navigation.findNAvController(view) the app crashes by the error: View does not have a navController set.

this is nav_graph:

<navigation 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:id="@+id/nav_graph"
    app:startDestination="@id/mainFragment">

    <fragment
        android:id="@+id/mainFragment"
        android:name="studio.apptick.mouj.view.fragments.MainFragment"
        tools:layout="@layout/fragment_main"
        android:label="fragment_main" >
        <action
            android:id="@+id/action_mainFragment_to_playlistActivityFragment"
            app:destination="@id/playlistActivityFragment" />
        <action
            android:id="@+id/action_mainFragment_to_searchActivity"
            app:destination="@id/searchActivity" />
    </fragment>
    <activity
        android:id="@+id/searchActivity"
        android:name="studio.apptick.mouj.view.activity.SearchActivity"
        android:label="activity_search"
        tools:layout="@layout/activity_search" />
</navigation>

this is fragment tag in activity:

        android:id="@+id/nav_host_fragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/view_player"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph">
    </fragment>

Answer

akshaysahai picture akshaysahai · Mar 8, 2020

I was facing the same issue, until I realized that we have to setup navControol onPostCreate function like this

@Override
public void onPostCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
    super.onPostCreate(savedInstanceState, persistentState);

    BottomNavigationView navigationView = findViewById(R.id.nav_view);


    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_memories, R.id.navigation_account)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.main_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);
}