How to save fragment state while using Navigation component and Bottom Navigation?

Viewed 2514

I have four fragment in bottom navigation and one activity, Bottom navigation is set up using NavController like this

navController = Navigation.findNavController(this, R.id.dashboardNavHostFragment).apply {
        setGraph(R.navigation.nav_graph , bundle)
    }
    bottomNavigationView.setupWithNavController(navController)

I'm passing some data in bundle that I require in my first fragment of bottom nav. The problem is it works fine the data comes in the fragment like this

private val args: PlayerFeedFragmentArgs by navArgs()
private var data: String? = args.name

but when I navigate using bottom nav and come back to my first fragment the data comes as null I tried saving data using

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putString("name", data)
}

and getting data back in onViewCreated but it didn't work because onSaveInstanceState does not get called when switching between fragments of bottom nav.

How can I save the incoming args from the activity in my first fragment so that when I switch fragments from bottom nav it stays the same.

1 Answers
Related