'Androidx Naviagtion - Pass custom object to destination fragment

I need to pass a custom object from one fragment to another fragment. I use androidx navigation for navigation between fragments. I had to use deepLink for navigation for my use case.

The navigation graph with the destination fragment has,

    <fragment
       android:id="@+id/ListFragment"
       android:name="com.joseph.learning.ListFragment"
       android:label="ListFragment">
    
       <argument android:name="todoItem"
        app:argType="com.joseph.learning.models.todoItem" />

      <deepLink app:uri="android-app://androidx.navigation/todoList/{todoItem}" />
  </fragment>

And from the source fragment, the navigation is initiated like

findNavController().navigate(
  Uri.parse("android-app://androidx.navigation/todoList/$item"),
  NavOptions.Builder()
      .setEnterAnim(R.anim.transition_slide_in_right)
      .setExitAnim(R.anim.transition_slide_out_left)
      .setPopExitAnim(R.anim.transition_slide_out_right)
      .setPopEnterAnim(R.anim.transition_slide_in_left)
      .build()
 )

But this fails as soon as it executes with below error

java.lang.UnsupportedOperationException: Parcelables don't support default values.
        at androidx.navigation.NavType$ParcelableType.parseValue(NavType.java:679)
        at androidx.navigation.NavType.parseAndPut(NavType.java:96)
        at androidx.navigation.NavDeepLink.parseArgument(NavDeepLink.java:306)
        ...

If incase, the custom object as argument is replaced with string or integer, then the navigation works without any issues. Also the passed data can be extracted in the destination fragment using navArgs()

What should be done to pass custom object across fragments ?



Solution 1:[1]

Android Documentation

Routes, deep links, and URIs with their arguments can be parsed from strings. This is not possible using custom data types such as Parcelables and Serializables as seen in the above table.

Solution: To pass around custom complex data, store the data elsewhere such as a ViewModel or database and only pass an identifier while navigating; then retrieve the data in the new location after navigation has concluded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arsalan Mehmood