i am using
navController.navigate(R.id.FragmentB)
to navigate from host fragment in MainActivity to navigate to different fragments and it works like expected except inside onActivityResult it won't respond ,i am returning an ID from other activity and want to navigate to Fragments depending on that ID but it is not responding ,
Navigation component navigate inside a onActivityResult not working
It turns out that i needed to create a Coroutine and run my navigation function on it , i tried with :
GlobalScope.launch(Dispatchers.Main) {
navigate()
}
and it works fine, obviously gotta need to optimise my coroutine ,but that was the main issue
can you explain more ? –
Deleterious
By invoking a coroutine that would run in Main dispatcher, internally it invokes
Handler.post
, which means that onActivityResult -> onStart -> onResume runs before your code. If you do it directly in onActivityResult, then onStart hasn't run, the NavController says its state is restored, and it ignores your navigate call. –
Mcneal If you're not using coroutines, a simple Handler()
will do the trick.
Handler().post {
navigate()
}
It turns out that i needed to create a Coroutine and run my navigation function on it , i tried with :
GlobalScope.launch(Dispatchers.Main) {
navigate()
}
and it works fine, obviously gotta need to optimise my coroutine ,but that was the main issue
Sounds like internally it's a
handler.post
. –
Mcneal can you explain more ? –
Deleterious
By invoking a coroutine that would run in Main dispatcher, internally it invokes
Handler.post
, which means that onActivityResult -> onStart -> onResume runs before your code. If you do it directly in onActivityResult, then onStart hasn't run, the NavController says its state is restored, and it ignores your navigate call. –
Mcneal © 2022 - 2024 — McMap. All rights reserved.
handler.post
. – Mcneal