Search code examples
androidandroid-architecture-componentsandroid-architecture-navigation

IllegalStateException: Link does not have a NavController set


I'm using Android Navigation Component for Navigation. I have a LoginFragment which has a button to transition to SignUpFragment. On clicking the button I'm getting this error.

java.lang.IllegalStateException: View android.support.v7.widget.AppCompatButton{49d9bd1 VFED..C.. ...P.... 201,917-782,1061 #7f090172 app:id/signUpLink} does not have a NavController set

Here is my nav_graph.xml

<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        app:startDestination="@id/loginFragment">
        <fragment
            android:id="@+id/loginFragment"
            android:name="org.test.oe.app.core.auth.login.LoginFragment"
            android:label="login_fragment"
            tools:layout="@layout/login_fragment">
            <action
                android:id="@+id/action_loginFragment_to_signUpFragment"
                app:destination="@id/signUpFragment" />
          
        </fragment>
    </navigation>

Here is the code in LoginFragment for Navigation -

binding.signUpLink.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_loginFragment_to_signUpFragment, null));

Here is extract from activity layout file for NavHostFragment -

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:name="android.navigation.fragment.NavHostFragment"
    app:navGraph="@navigation/main_navigation"
    app:defaultNavHost="true"/>

Solution

  • UPDATED SOLUTION

    Actually, Navigation can't find NavController in FrameLayout. So replacing <FrameLayout> with <fragment> will make it work .

    Add the following inside the <fragment> tag -

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

    After doing the changes, the code will look similar to this -

     <fragment
           android:id="@+id/fragment_container"
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           app:layout_behavior="@string/appbar_scrolling_view_behavior"
           android:name="androidx.navigation.fragment.NavHostFragment"
           app:navGraph="@navigation/main_navigation"
           app:defaultNavHost="true"/>