首页 > 解决方案 > 将 MutableList 或 ArrayList 从 Activity A 传递和检索到 B

问题描述

我需要通过这个:

private lateinit var memes: MutableList<Memes>

有这个模型:

class Memes (
    @SerializedName("id") var id: Long,
    @SerializedName("title") var title: String
)

从活动 a 到 b。

我已经看过几个“解决方案”,但没有一个有效!

这是我尝试过的最后一个:

    val extras = Bundle()
    val memesArrayList = ArrayList(memes)
    val i = Intent(context, GalleryShow::class.java)
    i.putExtras(extras)
    i.putStringArrayListExtra("list", memesArrayList)
    (context as Activity).startActivityForResult(i, 777)

不过,我Type mismatch: inferred type is ArrayList<Memes!> but ArrayList<String!>? was expected继续memesArrayList

编辑:

这是我现在的最新尝试:

在活动 A 里面的 recyclerview 项目中:

val extras = Bundle()

extras.putString("gal", "animals")
extras.putString("query", "")

val i = Intent(context, GalleryShow::class.java)
i.putExtra("list", memes.toTypedArray())
i.putExtras(extras)
(context as Activity).startActivityForResult(i, 777)

这是在活动 B 内部:

private lateinit var memes: MutableList<Memes>


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_gallery_show)

    memes = (this?.intent?.extras?.get("list") as? Array<Memes>)?.asList()!!.toMutableList()
}

标签: javaandroidkotlin

解决方案


您可以简单地使用intent.putExtra,而不必担心喜欢put_____Extra使用哪种变体。

提取值时,您可以使用intent.extras来获取 Bundle,然后您可以get()在 Bundle 上使用并转换为适当的类型。这比试图找出intent.get____Extra使用哪个函数来提取它更容易,因为无论如何你都必须强制转换它。

无论您的数据类是 Serializeable 还是 Parcelable,下面的代码都有效。您不需要使用数组,因为 ArrayList 本身是可序列化的,但您确实需要从 MutableList 转换为 ArrayList。

// Packing and sending the data:
val i = Intent(context, GalleryShow::class.java)
i.putExtra("list", ArrayList(memes)) // where memes is your MutableList<Meme> property
startActivityForResult(i, 777)

// Unpacking the data in the other activity:
memes = intent.extras?.get("list") as MutableList<Meme>

推荐阅读