I'm building a notes application basically a clone of keep notes. I want to save the note when the user press back button from the createNotesFragment and pop the fragment from the stack to move back to the homeFragment.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireActivity()
.onBackPressedDispatcher
.addCallback(this) {
saveNote()
activity?.supportFragmentManager?.popBackStack()
}
}
the navigation from the homeFragmet works fine but after adding one note when I try to move back to the createNotesFragment. It shows me this error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lavanianotesapp, PID: 7351
java.lang.IllegalArgumentException: Navigation action/destination com.example.lavanianotesapp:id/action_homeFragment_to_createNotesFragment cannot be found from the current destination Destination(com.example.lavanianotesapp:id/createNotesFragment) label=fragment_create_notes class=com.example.lavanianotesapp.UI.Fragments.CreateNotesFragment
at androidx.navigation.NavController.navigate(NavController.kt:1540)
I don't understant before popBaCckStack it works fine but after I pop the fragment it doesn't works.
Thanks in advance.
While working on a chat app for a client I found out the answer to my own question.
The reason behind navController didn't find the navigation at the currentDestination is because somehow it didn't updated the currentDestination after popping back stack it still thinks that the currentDestination is createNotesFragment and as there is no such action to move from the createNotesFragment to the same creatNotesFragment, it shows the error. The solution to this problem is: Create a extension function to NavController like below :
fun NavController.navigateSafely(
@IdRes resId : Int,
args : Bundle ? = null,
navOptions : NavOptions? = null,
navExtras : Navigator.Extras? = null
){
val action = currentDestination?.getAction(resId) ?: graph.getAction(resId)
if(action!=null && currentDestination?.id != action.destinationId){
navigate(resId,args,navOptions,navExtras)
}
}
Usage:
findNavController.navigateSafely(//Pass id)