java - 将 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()
}
解决方案
您可以简单地使用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>
推荐阅读
- java - 春天的远程
- google-cloud-platform - 下载 Google Cloud 存储库的最佳方式
- php - 如何检测除 application/octet-stream 之外的 .docx 正确 MIME
- c++ - 如何在 oc 类中获取私有 c++ 类型字段的值?
- javascript - Loopback 无法在不设置密码的情况下更新扩展模型
- android - ClassCastexception:不能转换为 android.support.v7.preference.Preference
- python - 一次绘制所有移动的对象,而不是绘制一个然后移动到下一个
- wordpress - 在 wordpress 元查询中排序无法正常工作
- c++ - Python - Django - C++ 中的繁重工作
- c# - C#中文件的相对路径?