Search code examples
androidkotlinnavigationandroid-safe-args

com.app.android.models.Item is not Serializable or Parcelable


Trying learn kotlin so any help would really appreciate. I am trying to pass this object between fragments and getting the message it's not serializable or parcelable. Any suggestions on why this would happen?


    @Serializable
    data class Item(
        @SerialName("_version")
        val version: String,
        @SerialName("language")
        val language: String,
        @SerialName("region")
        val region: String? = null,
        @SerialName("variant")
        val variant: String? = null
    )

nav_graph.xml


        <fragment
            android:id="@+id/fragment1"
            android:name="com.app.android.ui.fragment1">
    
            <action
                android:id="@+id/toFragment2"
                app:destination="@id/Fragment2"
             />
    
        
            <argument
                android:name="item1"
                android:defaultValue="@null"
                app:argType="com.app.android.models.Item"
                app:nullable="true" />
    
        </fragment>

It lets me pass other objects stored in the data section instead of the model section so not sure why this one is an issue. For example this object is fine as an argument:


    @Parcelize
    data class Item2 internal constructor(
        val code: String,
        val Id: String,
        val url: String,
    ) : Parcelable {
    
        companion object {
    
                //more code
        }
    }


Solution

  • The annotation helps the compiler, but you still need to implement the Serializable interface.

    @Serializable
    data class Item(
        @SerialName("_version")
        val version: String,
        @SerialName("language")
        val language: String,
        @SerialName("region")
        val region: String? = null,
        @SerialName("variant")
        val variant: String? = null
    ) : Serializable
    

    The reason that Item2 works is because it implements the Parcelable interface.