I’m using the Navigation Compose type-safe routes feature with Kotlin serialization. My routes are defined as @Serializable objects to achieve type safety in navigation. Everything works fine until the app is backgrounded, potentially killed, and then brought back. When returning to my app after switching to another one, I get the following error:
android.os.BadParcelableException: Parcelable encountered IOException writing serializable object (name = java.util.LinkedHashSet)
....
at android.app.servertransaction.PendingTransactionActions$StopInfo.collectBundleStates(PendingTransactionActions.java:123)
at android.app.servertransaction.PendingTransactionActions$StopInfo.run(PendingTransactionActions.java:139)
at android.os.Handler.handleCallback(Handler.java:959)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loopOnce(Looper.java:232)
at android.os.Looper.loop(Looper.java:317)
at android.app.ActivityThread.main(ActivityThread.java:8674)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:580)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:886)
Caused by: java.io.NotSerializableException: xxx.navigation.HomeRoute
here is how I set the route:
@Serializable
data object HomeRoute // route to Main screen
fun NavController.navigateToHome() = navigate(route = HomeRoute) {
popUpTo(graph.id)
}
fun NavGraphBuilder.homeScreen() {
composable<HomeRoute> {
HomeScreen()
}
}
I’m using Kotlin 2.0.21, and my navigation setup worked fine until I tested the scenario of leaving the app and coming back, like when the app opens the camera and gets back after taking the image. It seems that the navigation library attempts to restore the state but fails to serialize/deserialize my HomeRoute object.
Has anyone faced it before? or do we need any other setup? Any guidance or suggestions on handling this scenario would be greatly appreciated. Thanks for your reading !
The app is crashing because you haven't implemented the @Serializable interface, kotlin data classes/objects aren't serialisable by default, see for example: https://stackoverflow.com/a/61241564/4117097