Kotlin parcelable class throwing ClassNotFoundException
I guess this is a compatibility issue between Kotlin and Java for the moment. I found an easy solution that allows using only Kotlin and without boilerplate.
val intent = Intent(this, ProfilePage::class.java).apply {
extras?.putParcellable("clicked_person",person)
}
startActivity(intent)
And then to retrieve the value you should use:
var person = intent?.extras?.getParcellable<Person>("clicked_person")
NB: you don't need to cast as Person
After testing a solution in a comment, the following works without throwing any exception
Sending theParcelable
via Bundle
val intent = Intent(this, ProfilePage::class.java)
var bundle = Bundle()
bundle.putParcelable("selected_person",person)
intent.putExtra("myBundle",bundle)
startActivity(intent)
Recovering Parcelable
val bundle = intent.getBundleExtra("myBundle")
var person = bundle.getParcelable<Person>("selected_person") as Person
However, I do not know the difference with my old code in the question and why that old code throws Exception and why this new one does not throw
I've prepared the extension functions below for your convenience to use the Kotlin Parcelables without any warnings.
fun Intent.putParcel(key: String = "parcel_key", parcel: Parcelable) {
val bundle = Bundle()
bundle.putParcelable(key, parcel)
this.putExtra("parcel_bundle", bundle)
}
fun <T : Parcelable> Intent.getParcel(key: String = "parcel_key"): T? {
return this.getBundleExtra("parcel_bundle")?.getParcelable(key)
}
Usage:
//Put parcel
intent.putParcel(parcel = Person()) //any Parcalable
//Get parcel
val person: Person? = intent.getParcel() //auto converts using Generics