fun launchNextScreen(context: Context, people: People): Intent { val intent = Intent(context, NextScreenActivity::class.java) intent.putExtra(EXTRA_PEOPLE, (Parcelable) people) //intent.putExtra(EXTRA_PEOPLE, people as Parcelable) //intent.putExtra(EXTRA_PEOPLE, people) // tried above all three ways return intent }
I tried the above code to pass an instance of the People
class via intent using kotlin, but I am getting an error. What am I doing wrong?
Use gson to convert your object to JSON and pass it through intent. In the new Activity convert the JSON to an object. Its an overkill , gson is just a type of string serialization to json , its better to implement Serializable or Paracable .
One way to pass objects in Intents is for the object's class to implement Serializable. This interface doesn't require you to implement any methods; simply adding implements Serializable should be enough. To get the object back from the Intent, just call intent.
android studio will show you an error. Simple move your cursor to "People" and hit alt+enter. It should now show the option to generate a Parcelable implementation.
First, make sure the People
class implements the Serializable
interface:
class People : Serializable { // your stuff }
Inner fields of People
class must also implement the Serializable
interface, otherwise you'll get runtime error.
Then it should work:
fun launchNextScreen(context: Context, people: People): Intent { val intent = Intent(context, NextScreenActivity::class.java) intent.putExtra(EXTRA_PEOPLE, people) return intent }
To receive people back from Intent you'll need to call:
val people = intent.getSerializableExtra(EXTRA_PEOPLE) as? People
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