Search code examples
androidkotlindata-classsealed-class

How to pass data class as Parcelable in a bundle?


I have a sealed class like so:

sealed class SealedClass {

    object Object1 : SealedClass()
    object Object2 : SealedClass()
    object Object3 : SealedClass()

    data class DataClass(val sealedClass: SealedClass, val anotherDataType: AnotherDataType? = null)
}

I would like to pass my data class in a Bundle like we normally pass values to a new fragment like so:

@JvmStatic
fun newInstance(dataClass: DataClass): Fragment {
    val fragment = Fragment()

    val args = Bundle(1)
    args.putParcelable("DATA_CLASS", dataClass)
    fragment.arguments = args

    return fragment
}

I'm not sure how to go about this. So far what I've read is that people use an @Parcelize annotation, which is an experimental feature of Kotlin that I'm trying to avoid. Another approach is to extend the data class by Parcelable and implement the Parcelable methods, but since I use custom classes as parameters in the DataClass (for instance, SealedClass), I don't know how to read/write those values inside Parcelable implementation. Is this not a right approach to go about it?


Solution

  • Serializable while using reflection and causing a bit more garbage collection, is easier to implement.

    I find it easiest to use GSON. https://github.com/google/gson

    First, add it to your data class like this:

    data class TimeSeries(
        @SerializedName("sourceInfo")
        val sourceInfo: SourceInfo? = null,
        @SerializedName("variable")
        val variable: Variable? = null,
        @SerializedName("values")
        val values: List<Value_>? = null,
        @SerializedName("name")
        val name: String? = null
    ) : Serializable
    

    Then pass it in your bundle:

    val intent = Intent(context, DetailsActivity::class.java).apply {
                putExtra(MY_DATA, Gson().toJson(mydata[position]))
            }
            context.startActivity(intent)
    

    Then bring it in through your bundle:

    mydata = Gson().fromJson(intent?.extras?.getString(MY_DATA), TimeSeries::class.java)