Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Pass custom object via intent in kotlin

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?

like image 443
Ankit Kumar Avatar asked Dec 01 '17 12:12

Ankit Kumar


People also ask

How do you pass an object through intent?

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 .

Can we pass object through intent in android?

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.

How do I send Parcelable intent kotlin?

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.


1 Answers

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 
like image 52
A. Shevchuk Avatar answered Sep 30 '22 23:09

A. Shevchuk