Search code examples
javaandroidandroid-fragmentsandroid-jetpack-navigation

Exception when trying to navigate to another fragment


I recently started exploring with the Nav component and I stumbled into this Fragment HomeContainerFragment{e1561bc} (156e8ba6-f284-4c85-a4bb-82a63069888b)}notassociated with a fragment manager. Huh? But that's a fragment. I could even navigate to it using fragment transaction replace. The error points to the findNavController:

NavDirections navDirections = LoginFragmentDirections.actionLoginFragmentToHomeContainerFragment();

NavHostFragment.findNavController(HomeContainerFragment.newInstance()).navigate(navDirections)

This HomeContainerFragment.newInstance() returns this new HomeContainerFragment()


Solution

  • I misunderstood the argument for findNavController. I thought it was supposed to be the fragment that was going to replace the current one. I was wrong. It's supposed to be the current fragment, not the next one.

    So changing it to: findNavController(this) fixed it.