安卓通过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。

扫描二维码关注公众号,回复: 3200120 查看本文章
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());
}

猜你喜欢

转载自blog.csdn.net/yinxing2008/article/details/82466234