Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 215
Sankar Avatar asked Oct 14 '25 03:10

Sankar


1 Answers

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())
like image 62
Sankar Avatar answered Oct 18 '25 12:10

Sankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!