美文网首页安卓开发
安卓通过Parcelable传值失败解决方案及原理分析

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

作者: 蓝不蓝编程 | 来源:发表于2018-10-12 09:11 被阅读9次

问题描述

在项目中,需要从一个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给读取出来。

image.png

验证:

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

验证OK。

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

正确的做法:

方式一(推荐):

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

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

方式二:

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://www.jianshu.com/p/442339952f26

相关文章

网友评论

    本文标题:安卓通过Parcelable传值失败解决方案及原理分析

    本文链接:https://www.haomeiwen.com/subject/oedwaftx.html