I have two fragments A and B. I'm trying to navigate to B and then back to A. While doing this, I have some form data (a bunch of text fields) in A which I'd like to preserve while navigating back and forth to B. When I navigateUp()
from B, the data in A is preserved but I'm not able to pass data from B to A. If I use bundles while navigating back to A, I'm unable to save the data using onSaveInstanceState(). I've used the following code in fragment A for saving the form data (got it from: https://developer.android.com/guide/components/activities/activity-lifecycle#instance-state)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(savedInstanceState!=null){
with(savedInstanceState) {
inputName.setText(getString("Name"))
}
}
else{
//I just leave it since the text fields will be empty anyways
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState.run {
putString("Name",inputName.text.toString())
}
super.onSaveInstanceState(outState)
}
But onSaveInstaceState is not being called when I navigate away (due to this when onCreate is called, the value ends up as null and the flow goes to the if statement). All I want to do is to save data in A while navigating from A to B.
Not the best approach to follow (I'd suggest to share data using shared stateful view model but from your question it is not clear if you are using view models at all) :
<action
android:id="@+id/backToA"
app:destination="@+id/A"
app:popUpTo="@+id/B"
app:popUpToInclusive="true" />
navigateUp
use navigate
with action backToA
and supply arguments you need to provide to AYou'll also have to take care of manual handling of "back by system back button" scenario (to override navigateUp), as well as, possibly, "back by toolbar back" if you have toolbar - but that's another story.