Reputation: 743
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:
Upvotes: 3
Views: 5399
Reputation: 373
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)
}
}
Upvotes: 1
Reputation: 2511
You don't need to find your navHostFragment to navigate
val root = inflater.inflate(R.layout.fragment_host, container, false)
root.host_text_view.setOnClickListener {
Log.d("Tag", "clicked")
if (findNavController().currentDestination?.id == hostFragment)
findNavController().navigate(R.id.action_hostFragment_to_secondFragment)
}
You can check for Kotlin methods to navigate https://developer.android.com/guide/navigation/navigation-navigate
Upvotes: 0