Skip to content
Advertisement

Activity does not have a NavController set on

I basically set up 3 fragments for my bottom navigation view with all linked to activity.xml

activity.xml where I put fragment tag.

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView2"
    app:navGraph="@navigation/my_nav"
    android:layout_width="409dp"
    android:layout_height="599dp" />

My Activity.java code (specifically):

BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
NavController navController = Navigation.findNavController(this, R.id.fragment);
NavigationUI.setupWithNavController(bottomNavigationView, navController);

The problem now is that if I run that same java code using fragment tag in xml, it runs well but suggests I use <androidx.fragment.app.FragmentContainerView(linters) but on using <androidx.fragment.app.FragmentContainerView, it displays the error in the Logcat.

Activity does not have a NavController set on

I’ve seen a lot of similar errors and fixes for that on this site like FragmentContainerView as NavHostFragment

But the problem now is that most of them post Kotlin codes and the few java codes I tried didn’t work for me

or who can translate this code to java:

val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController

Advertisement

Answer

You can get the Nav Controller using Java like this:

final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
final NavController navController = navHostFragment.getNavController();

And then you setup your bottom navigation like this:

NavigationUI.setupWithNavController(bottomNavigationView, navController);

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement