Android Studio: Navigation Component not preserving state on Screen Rotation
I've hit a wall trying to I'm sure I'm missing something obvious here, but I'm facing an issue with the Android Navigation Component where the state of my fragment is not preserved after a screen rotation. I'm using Android Studio Bumblebee (2021.1.1) and targeting SDK version 31. My setup involves a ViewModel that holds some data, but upon rotating the device, the app navigates back to the starting fragment instead of retaining the current fragment and its state. Here's a simplified version of my navigation setup: ```xml <fragment android:id="@+id/fragment_sample" android:name="com.example.app.SampleFragment" android:label="Sample" tools:layout="@layout/fragment_sample"> <action android:id="@+id/action_sample_to_detail" app:destination="@id/fragment_detail" /> </fragment> ``` In my `MainActivity`, I have the following code to set up navigation: ```kotlin class MainActivity : AppCompatActivity() { private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) navController = findNavController(R.id.nav_host_fragment) } } ``` In `SampleFragment`, I initialize my ViewModel and set some data: ```kotlin class SampleFragment : Fragment() { private lateinit var viewModel: SampleViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel = ViewModelProvider(this).get(SampleViewModel::class.java) // Initializing data viewModel.data = "Some data" return inflater.inflate(R.layout.fragment_sample, container, false) } } ``` I tried adding `setRetainInstance(true)` in my fragment's `onCreate`, but it didn't resolve the issue. I'm unsure if I am missing something in the ViewModel setup or if thereβs a specific way to handle navigation state with this setup. Iβve also checked that Iβm using AndroidX libraries. Any insights on how to retain the fragment state across rotations would be greatly appreciated! The project is a CLI tool built with Kotlin. Thanks for taking the time to read this! Thanks in advance!