1

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 ?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

4 Comments

What if you have to value type 'Any' and 'list or another data class'
Any won't work. Lists and other data classes will work as long as they are Parcelable or Serializable.
that means I have to specify return type
but sometimes I received String or Int . how to handle such condition
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.