How to Pass custom object via intent in kotlin

AndroidAndroid IntentKotlinKotlin Android-Extensions

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

Implement Serializable in the object:

data class Object (
        var param1: Int? = null,
        var param2: String? = null
) : Serializable

or

class Object : Serializable {
        var param1: Int? = null,
        var param2: String? = null
}

Then, you can pass the object using Intent:

val object = Object()
...
val intent = Intent(this, Activity2::class.java)
intent.putExtra("extra_object", object as Serializable)
startActivity(intent)

Finally, in Activity2 you get the object with:

val object = intent.extras.get("extra_object") as Object

Solution 3 - Android

Found a better way of doing this:

In your gradle:

apply plugin: 'org.jetbrains.kotlin.android.extensions'

android {
    androidExtensions {
        experimental = true
    }
}

In your data class:

@Parcelize
data class Student(val id: String, val name: String, val grade: String) : Parcelable

In source activity:

val intent = Intent(context, Destination::class.java)
        intent.putExtra("student_id", student)
        context.startActivity(intent)

In destination activity:

student = intent.getParcelableExtra("student_id")

Solution 4 - Android

##Parcelize is no longer experimental, as of Kotlin 1.3.60+!

Define a data class, adding @Parcelize annotation and extending Parcelable:

@Parcelize
data class People(val id: String, val name: String) : Parcelable

To add to intent:

val intent = Intent(context, MyTargetActivity::class.java)
intent.putExtra("people_data", student)
context.startActivity(intent)

In MyTargetActivity:

val people: People = intent.getParcelableExtra("people_data")

If you haven't yet, enable extensions in your app's build.gradle. This also enables data binding and other great advanced features

apply plugin: 'kotlin-android-extensions'

Solution 5 - Android

I found a better way to pass an object from one activity to another using Parcelable, it is faster than Serialization Android: Difference between Parcelable and Serializable?

first, add these lines of code inside build.gradle(app)

apply plugin: 'kotlin-android-extensions' in app.grable 

@Parcelize 
class Model(val title: String, val amount: Int) : Parcelable

passing with Intent--->

val intent = Intent(this, DetailActivity::class.java)
intent.putExtra(DetailActivity.EXTRA, model)
startActivity(intent)

Getting from intent --->

val model: Model = intent.getParcelableExtra(EXTRA)

Solution 6 - Android

This post might be useful for what you intend to do:

https://stackoverflow.com/questions/33551972/is-there-a-convenient-way-to-create-parcelable-data-classes-in-android-with-kotl

Basically, kotlin provides some little extras:

@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable

See the post for more info.

Solution 7 - Android

in kotlin to start activity and pass some data you could try something like this:

startActivity(intentFor<NameOfActivity>(STRING to data))

Have Fun

Solution 8 - Android

you have to add the type inside <>...its working for me

val people = intent.getParcelableExtra<People>(EXTRA_PEOPLE) as People

In your PeopleDetailActivity activity, initialize viewModel in onCreate

viewModel = this@PeopleDetailActivity.viewModel.apply { postPeopleId(getPeopleFromIntent().id) }

And also initialize this method :

private fun getPeopleFromIntent() = intent.getParcelableExtra<People>(peopleId) as People

Write below code for passing the intent extras :

companion object {
        private const val objectId = "people"
        fun startActivityModel(context: Context?, people: People) {
            if (context != null) {
                val intent = Intent(context, PeopleDetailActivity::class.java).apply {
                    putExtra(
                        objectId,
                        people
                    )
                }
                context.startActivity(intent)
            }
        }
    }

Call the above method in your PeopleListViewHolder onClick

override fun onClick(v: View?) = PeopleDetailActivity.startActivityModel(context(), people)

Solution 9 - Android

Your People class needs to implement Parcelable like this:

class People(): Parcelable{
// stuff


}

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.

This generated code will contain something like

parcel.writeString(member1)
parcel.writeInt(member2)

and somewhere else

member1=parcel.readString()
member2=parcel.readInt()

Make sure that all members are contained in these methods and when modifying it, make sure that read and write is happening in the exact same order.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkit KumarView Question on Stackoverflow
Solution 1 - AndroidA. ShevchukView Answer on Stackoverflow
Solution 2 - Androidfireb86View Answer on Stackoverflow
Solution 3 - AndroidAnkit KumarView Answer on Stackoverflow
Solution 4 - AndroidGiboltView Answer on Stackoverflow
Solution 5 - AndroidAshik AzeezView Answer on Stackoverflow
Solution 6 - AndroidJavatarView Answer on Stackoverflow
Solution 7 - AndroidRafael FilipakeView Answer on Stackoverflow
Solution 8 - AndroidGauresh KambliView Answer on Stackoverflow
Solution 9 - AndroidAdrian KView Answer on Stackoverflow