Search code examples
androidkotlinandroid-navigation-graph

NullPointerException when trying to get NavController


I cannot understand what is the reason for the error java.lang.NullPointerException: null cannot be cast to non-null type androidx.navigation.fragment.NavHostFragment

This is my host fragment:

class HostFragment : Fragment() {
    
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_host, container, false)

        // error here
        val navHostFragment = requireActivity().supportFragmentManager.findFragmentById(R.id.hostFragment) as NavHostFragment
        //

        val navController = navHostFragment.navController

        root.host_text_view.setOnClickListener {
            Log.d("Tag", "clicked")

            navController.navigate(R.id.action_hostFragment_to_secondFragment)
        }

        return root
    }
}

I want to navigate to SecondFragment by clicking on the textView. And back.

And nav graph .xml file:

<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/hostFragment">

    <fragment
        android:id="@+id/hostFragment"
        android:name="com.example.test.HostFragment"
        android:label="fragment_host"
        tools:layout="@layout/fragment_host" >
        <action
            android:id="@+id/action_hostFragment_to_secondFragment"
            app:destination="@id/secondFragment" />
    </fragment>

    <fragment
        android:id="@+id/secondFragment"
        android:name="com.example.test.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second" >
        <action
            android:id="@+id/action_secondFragment_to_hostFragment"
            app:destination="@id/hostFragment" />
    </fragment>
</navigation>

The Navigation graph has its final form like: enter image description here


Solution

  • best way to use Navigation Graph is after the view is created, since some view takes time to create so u might get this exception as your view is still in processing or creating the view.

    so to avoid this , u can use OnViewCreated() as

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
           super.onViewCreated(view, savedInstanceState)
           navController = Navigation.findNavController(view)
        
           view.imgNumbrLookUp.setOnClickListener { 
                navController.navigate(R.id.action_homeFragment_to_webActivity) 
           }       
    }