我有几个活动,我使用Intents在它们之间传递数据。我想从第一个活动传递我的自定义对象的数组,并使其成为第二个活动中的arraylist。我的代码是:
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 ?
}
}
现在我的问题是,将ActivityA中的attachments
数组提供给ActivityB中attachments
数组列表的最有效方法是什么?
答案 0 :(得分:4)
答案很简单。
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())