Search code examples
android-intentkotlinparcelable

Kotlin parcelable class throwing ClassNotFoundException


I have a class that I use as my data model for a RecyclerViewin order to pass object of this class from one activity to another via Intent I had to make it Parcelable

The problem is now that I am being able to send the object from one activity to another and retrieve it, so that the app does not crash, but keeps throwing ClassNotFoundException in the logcat screen.

What am I doing wrong?

----> Person.kt

@Parcelize
class Person(var name: String, var username: String, var address: String, val avatar: Int) : Parcelable

----> in MainActivity.kt

val intent = Intent(this, ProfilePage::class.java)
        intent.putExtra("clicked_person",person)
        startActivity(intent)

---->. onCreate() in ProfilePAge.kt

var person  = intent.getParcelableExtra<Person>("clicked_person") as Person

And the Exception

E/Parcel: Class not found when unmarshalling: com.example.testkot.kotlinapp.Person
                                         java.lang.ClassNotFoundException: com.example.testkot.kotlinapp.Person

Please remember that the app does not crash, it keeps working but shows the exception in logcat


Solution

  • 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