Intent传递数据时,需要注意的点

一般页面之间传递对象为了方便直接使用Intent,intent.putExtra(“”,parcelable);

使用后会报一个这样的错,应用正常运行。
这里写图片描述

将对象存入Bundle中,Bundle存入Intent中再传就不会出现报错。
但是,有些时候直接使用Intent传也不会报错。

下面是引自 http://blog.csdn.net/rooney8/article/details/41308495?utm_source=tuicool&utm_medium=referral

两个Activity之间传递数据,数据的附加有两种方式:
一种是直接 intent.putxx();
另一种是 先bundle.putxx(), 然后再调用public Intent putExtras (Bundle extras) 添加bundle.
其实两种的本质是一样的。
先看Intent的方法:

public Intent putExtra(String name, boolean value) {

if (mExtras == null) { 

mExtras = new Bundle(); 

} 

mExtras.putBoolean(name, value); 

return this; 

} 

其中mExtras是intent内部定义的一个private Bundle变量。
可以看到,intent其实是调用了bundle相应的put函数,也就是说,intent内部还是用bundle来实现数据传递的,只是封装了一层而已。

而使用Bundle传值的话最后调用的方法:Intent.putExtras(Bundle extras):

public Intent putExtras(Bundle extras) {

if (mExtras == null) { 

mExtras = new Bundle(); 

} 

mExtras.putAll(extras); 

return this; 

} 

可以看到,其实是把之前那个bundle中的数据批量添加到intent内部的bundle中。
Intent旨在数据传递,bundle旨在存取数据,当然intent也提供一部分数据的存取,但比起bundle就显得不专业,不灵活的多


找了很久还是没有找到会报上面那个错的原因,如果知道的大佬请告诉我下,蟹蟹!

猜你喜欢

转载自blog.csdn.net/zhangli_/article/details/78433232