In my project I have a main activity which host the default navController. From the default nav-graph, I can navigate to all the hosted fragments. I after the onResume()
method of each fragment I check the authentication state, If the user is not authenticated the user will be navigated to the login fragment. So instead of checking the authentication state in each fragment which will lead to lots of code duplication. I want to check the authentication state in the onResume()
method of the main activity then navigate appropriately. I have tried calling navController.navigate($fragmentId)
and some of its variants. It usually navigate to the destination activity. But when I tried to navigate to another fragment from the login fragment I receive this error
java.lang.IllegalStateException: Fragment LoginFragment{de25d51} (1c765036-4d65-41dc-8dec-549281d50db6)} not attached to an activity.
I created a global action on the nav graph of the activity I want to navigate to like this
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_nav"
app:startDestination="@id/mainFragment">
...
<action android:id="@+id/action_global_mainFragment"
app:destination="@id/mainFragment"/>
</navigation>
then after checking the authentication state, I call the nav action in the enclosing activity like this
this.findNavController(R.id.activity_nav_host_fragment).navigate(R.id.action_global_mainFragment)
Feel free to read more about global actions here