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?
I think this can be simpler now with recent Kotlin using Parcelable:
@Parcelize
data class TimeSeries(
val sourceInfo: SourceInfo? = null,
val variable: Variable? = null,
val values: List<Value_>? = null,
val name: String? = null
) : Parcelable
Then pass it in your bundle:
val intent = Intent(context, DetailsActivity::class.java).apply {
putExtra(MY_DATA, mydata[position])
}
context.startActivity(intent)
Then bring it in through your bundle:
mydata = intent?.getParcelableExtra<TimeSeries>(MY_DATA)
If you want instead to pass a Bundle
you can also just use bundleOf(MY_DATA to mydata[position])
when putting the Extra, and intent?.getBundleExtra(MY_DATA)?.getParcelable<TimeSeries>(MY_DATA)
when getting it, but looks like adding another layer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With