我如何接收可打包的包裹?
Posted
技术标签:
【中文标题】我如何接收可打包的包裹?【英文标题】:How do I receive parcelable bundles? 【发布时间】:2018-12-11 08:18:51 【问题描述】:我创建一个这样的包:
val intent = Intent(classContext, Recipes::class.java)
var bundle = Bundle().apply
putParcelableArrayList("LIST", ArrayList<Parcelable>(fbModel.recipeArray))
putInt("POSITION", position)
intent.putExtra("bundle", bundle)
//CHECK TO SEE IF DATA IS STORED
var passedIntent = intent.extras
var bundle2: Bundle = passedIntent.getBundle("bundle")
var recipeArray: ArrayList<RecipeTemplate> = bundle2.getParcelableArrayList("LIST")
Log.d("TAGC", " " + recipeArray[0].recipeHeader) //SUCCESS!
Log.d("TAGC", " " + position) //SUCCESS!
startActivity(intent)
为了查看它是否有效,我从 bundle
创建并记录了变量,它们确实包含正确的数据。
存储在数组RecipeTemplate
中的类对象为Parcelized
,如下所示:
@SuppressLint("ParcelCreator")
@Parcelize
class RecipeTemplate: Parcelable
var recipeHeader: String? = null
var recipeText: String? = null
var recipeImage: String? = null
var recipeKey: String? = null
到目前为止一切顺利。但是,当我在其他活动中收到捆绑包时,它出于某种原因返回 null,即使我使用与上面相同的确切代码(测试代码以查看捆绑包是否存储了正确的数据)。这是接收活动:
var passedIntent: Bundle = intent.extras
var bundle = passedIntent.getBundle("bundle")
var counter: Int = bundle.getInt("POSITION", 0)
var recipeArray: ArrayList<RecipeTemplate> = bundle.getParcelableArrayList("LIST")
Log.d("TAGA", "PASSED " + counter) //SUCCESS
Log.d("TAGA", "PASSED " + recipeArray[0].recipeHeader) //FAIL: null
计数器/位置变量返回正确的数据,但 recipeArray
出于某种原因为空。同样,它在之前的活动中有效,所以我不明白为什么这次会有所不同......有什么想法吗?
更新
如果我将光标悬停在类中的变量上,它会显示:Property not serialized as parcel
。听起来事情并没有按我的预期工作......这是什么原因?
【问题讨论】:
您确定您的食谱图片不为空吗?因为在第一个活动中,您正在检查配方标题。在第二个,您正在检查图像。 哦,那只是我尝试不同的对象变量。我确定它不为空。我会更新问题。感谢您指出:) 我会尝试提出一个答案。请确认它有效:) 【参考方案1】:尝试重构您的 RecipeTemplate 以在构造函数中接受属性作为参数。
@SuppressLint("ParcelCreator")
@Parcelize
class RecipeTemplate (
var recipeHeader: String? = null,
var recipeText: String? = null,
var recipeImage: String? = null,
var recipeKey: String? = null
) : Parcelable
问题可能出在 parcelize 的实施方式上。我找不到任何关于此的文档,但 createFromParcel 很有可能只调用主构造函数。这仍然是实验性的,将来可能会改变。不过我可能是错的,我很高兴得到纠正。
【讨论】:
您刚刚添加了: Parcelable
吗?我试过了,但它说Expecting a top level declaration
我移动了括号内的所有属性(你的是花括号)并在最后移动了界面。也添加了逗号,因为它们已经是参数
老兄,成功了!了不起的人。非常感谢您花时间帮助我! :D 你认为你能详细说明一下我刚刚做了什么吗?
这与Kotlin如何实现Parcelize有关。在您之前的类定义中,所有内容都被声明为属性。因此,当您使用默认构造函数实例化您的类时,您必须手动初始化您的属性。我认为 Parcelize 仅调用主构造函数,因此,它可以实例化您的类,但不能设置属性值。这就是为什么一切都是空的。要解决这个问题,您必须将属性设置为主要构造函数参数,以便 parcelize 可以设置它们的值。
请注意,@Parcelize 是一项实验性功能。未来的实现和规范可能会发生变化,所以要小心。以上是关于我如何接收可打包的包裹?的主要内容,如果未能解决你的问题,请参考以下文章