安卓通过Parcelable传值失败解决方案及原理分析

问题描述

   在项目中,需要从一个Activity传值到另一个Activity,因为涉及参数较多,所以定义一个Parcelable对象来传值。但是结果接收的地方没有获取到。

   代码如下(代码做了简化):   

public String title;
public void writeToParcel(Parcel dest, int flags) {
    dest.writeValue(this.title);
}

protected TransInfo(Parcel in) {
    this.title = in.readString();
}

问题原因:

   因为写的时候,用的时writeValue,而读取的时候用的是readString,不配对。应该写的时候用writeString方法。

原因分析:

   深入Parcel.java源代码查看writeValue方法:其实writeValue方法也调用了writeString,但是在之前还调用了writeInt,所以不能直接readString,除非先把这个写如的Int给读取出来。

验证: 

   基于上面的分析,我修改了代码,增加了“in.readInt();”。

   验证OK。

protected TransInfo(Parcel in) {
	in.readInt();
	this.title = in.readString();
}

正确的做法:

方式一(推荐):

public String title;
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.title);
}

protected TransInfo(Parcel in) {
	this.title = in.readString();
}

方式二:

public String title;
public void writeToParcel(Parcel dest, int flags) {
    dest.writeValue(this.title);
}

protected TransInfo(Parcel in) {
	this.title = (String)in.readValue(String.class.getClassLoader());
}

安卓开发技术分享:https://blog.csdn.net/yinxing2008/article/details/84555061

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值