Search code examples
androidkotlinkotlin-android-extensionskotlin-extension

Kotlin pass array of custom objects via Intents and receive as a ArrayList


I have a couple of activities and I pass data between them using Intents. I want to pass an array of my custom object from the first activity and make it an arraylist in the second activity. The code that I have is:

data class Attachment(val Name: String, val Content: String)

class ActivityA {
    private var attachments: Array<Attachment> = arrayOf()
    fun callB() {
        intent = Intent(this,ActivityB::class.java).apply {
            putExtra("Attachments", attachments)
        }
    }
}

class ActivityB {
    private var attachments: ArrayList<Attachment>?

    override fun onCreate(savedInstanceState: Bundle?) {
        // How do I get the passed array and store in the arraylist here ?

        val a: Array<Attachment> = intent.getParcelableArrayExtra("Attachments") as Array<Attachment>
        attachments = a // fails with a type mismatch error
        attachments = ArrayList(a) // fails again
        attachments = intent.get????????("Attachments") // any such option ?
    }
}

Now my question is, what is the most efficient way to get the attachments array in ActivityA to the attachments array-list in the ActivityB ?


Solution

  • The answer is simple.

    data class Attachment(val Name: String, val Content: String) : Serializable
    
    // In ActivityB
    val a: Array<SecretJSON.Attachment> = intent.getSerializableExtra("Attachments") as Array<Attachment>
    attachments = a.toCollection(ArrayList())