Reputation: 51
I want to convert below .tostring to data class how to convert?
InstrumentResponse(AGM=false, AllOrNone=true, Bonus=true, Dividend=true, EGM=false, AuctionDetailInfo=AuctionDetailInfo(AuctionNumber=0, AuctionStatus=0, InitiatorType=0)
What I am trying to do to pass data class though bundle from one fragment to another but doing with bundle.putString
how to convert this again to a data class ?
Is there a better way to achieve ? or how to convert dataClass.toString
to Data class ?
Upvotes: 1
Views: 7686
Reputation: 9881
To pass data class between activities, don't use toString. Instead, use putParcelable
. A parcelable is a custom serialization format for Android. See the official documentation (with examples) here.
If you don't want to dig into Parcelable
implementation details, you can use the kotlin experimental features.
Starting from Kotlin 1.1.4, Android Extensions plugin provides
Parcelable
implementation generator as an experimental feature.
In short, add
androidExtensions {
experimental = true
}
to your build.gradle
, then use the @Parcelize
annotation in your data class and make it inherit from Parcelable
:
import kotlinx.android.parcel.Parcelize
@Parcelize
class InstrumentResponse(...): Parcelable
Upvotes: 0
Reputation: 43841
You should just use @Parcelize
.
Add
androidExtensions {
experimental = true
}
to you build.gradle
.
Then add the annotation to you class
@Parcelize
data class InstrumentResponse(...)
Then put the value directly into the Bundle
bundle.putParcelable(key, instrumentReponse)
To retrieve the value, call
val instrumentReponse = bundle.getParcelable<InstrumentResponse>(key)
Upvotes: 1