Android Parcelable不支持默认值导致应用崩溃
创始人
2024-08-14 23:00:40
0

在Android开发中,Parcelable是一种用于在不同组件之间传递数据的接口。然而,Parcelable不支持默认值,这可能导致应用崩溃。为了解决这个问题,你可以使用Bundle来传递数据,而不是直接使用Parcelable。

以下是一个使用Bundle传递数据的示例代码:

首先,创建一个包含数据的类,该类实现Parcelable接口:

public class MyData implements Parcelable {
    private String name;
    private int age;

    public MyData(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 实现Parcelable接口的方法
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
    }

    // 添加一个静态的Parcelable.Creator接口实例化器
    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        @Override
        public MyData createFromParcel(Parcel source) {
            return new MyData(source);
        }

        @Override
        public MyData[] newArray(int size) {
            return new MyData[size];
        }
    };

    // 添加一个私有构造函数,用于从Parcel中读取数据
    private MyData(Parcel source) {
        name = source.readString();
        age = source.readInt();
    }

    // 添加getter和setter方法
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

然后,在发送方的Activity中,将数据打包到Bundle中,然后将Bundle作为Intent的Extra传递给接收方的Activity:

// 创建MyData对象
MyData myData = new MyData("John", 25);

// 创建一个Bundle对象,并将MyData对象放入其中
Bundle bundle = new Bundle();
bundle.putParcelable("data", myData);

// 创建一个Intent对象,并将Bundle作为Extra传递给接收方的Activity
Intent intent = new Intent(SenderActivity.this, ReceiverActivity.class);
intent.putExtras(bundle);
startActivity(intent);

在接收方的Activity中,从Intent中获取Bundle,并从Bundle中获取MyData对象:

// 从Intent中获取Bundle
Bundle bundle = getIntent().getExtras();

// 从Bundle中获取MyData对象
MyData myData = bundle.getParcelable("data");

// 使用MyData对象的数据
String name = myData.getName();
int age = myData.getAge();

使用Bundle传递数据可以避免Parcelable不支持默认值导致应用崩溃的问题。

相关内容

热门资讯

记者揭秘!智星菠萝辅助(透视辅... 记者揭秘!智星菠萝辅助(透视辅助)拱趴大菠萝辅助神器,扑克教程(有挂细节);模式供您选择,了解更新找...
一分钟揭秘!约局吧能能开挂(透... 一分钟揭秘!约局吧能能开挂(透视辅助)hhpoker辅助靠谱,2024新版教程(有挂教学);约局吧能...
透视辅助!wepoker模拟器... 透视辅助!wepoker模拟器哪个好用(脚本)hhpoker辅助挂是真的,科技教程(有挂技巧);囊括...
透视代打!hhpkoer辅助器... 透视代打!hhpkoer辅助器视频(辅助挂)pokemmo脚本辅助,2024新版教程(有挂教程);风...
透视了解!约局吧德州真的有透视... 透视了解!约局吧德州真的有透视挂(透视脚本)德州局HHpoker透视脚本,必胜教程(有挂分析);亲,...
六分钟了解!wepoker挂底... 六分钟了解!wepoker挂底牌(透视)德普之星开辅助,详细教程(有挂解密);德普之星开辅助是一种具...
9分钟了解!wpk私人辅助(透... 9分钟了解!wpk私人辅助(透视)hhpoker德州透视,插件教程(有挂教学);风靡全球的特色经典游...
推荐一款!wepoker究竟有... 推荐一款!wepoker究竟有透视(脚本)哈糖大菠萝开挂,介绍教程(有挂技术);囊括全国各种wepo...
每日必备!wepoker有人用... 每日必备!wepoker有人用过(脚本)wpk有那种辅助,线上教程(有挂规律);wepoker有人用...
玩家必备教程!wejoker私... 玩家必备教程!wejoker私人辅助软件(脚本)哈糖大菠萝可以开挂,可靠技巧(有挂神器)申哈糖大菠萝...