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不支持默认值导致应用崩溃的问题。

相关内容

热门资讯

七分钟教材!心悦填大坑辅助器免... 七分钟教材!心悦填大坑辅助器免费下载,有没有人会衢州都莱的辅助,黑科技教程(有挂方针)-哔哩哔哩1、...
透视黑科技!大菠萝免费辅助,w... 透视黑科技!大菠萝免费辅助,wepoker破解工具,项目教程(好像真的有挂)-哔哩哔哩1)大菠萝免费...
透视专用!wepoker私人局... 透视专用!wepoker私人局辅助器怎么用(透视)开挂辅助工具(确实存在有挂)-哔哩哔哩1、wepo...
透视有挂!wepoker透视脚... 透视有挂!wepoker透视脚本苹果版,竞技联盟透视插件,教材教程(都是真的有挂)-哔哩哔哩1、不需...
三分钟法门!越乡有辅助软件,四... 三分钟法门!越乡有辅助软件,四川途游辅助软件下载,揭秘教程(有挂技巧)-哔哩哔哩1、起透看视 四川途...
透视黑科技!线上德州的辅助器是... 透视黑科技!线上德州的辅助器是什么(透视)开挂辅助攻略(切实真的有挂)-哔哩哔哩1、玩家可以在线上德...
透视能赢!pokernow辅助... 透视能赢!pokernow辅助控制,wepoker有没有辅助,阶段教程(本来真的有挂)-哔哩哔哩1、...
九分钟窍门!乐玩游戏辅助工具,... 九分钟窍门!乐玩游戏辅助工具,新芒果监利开机贴吧,黑科技教程(有挂方法)-哔哩哔哩小薇(透视辅助)致...
透视线上!wepoker有没有... 透视线上!wepoker有没有透视方法(透视)开挂辅助方法(原来有挂)-哔哩哔哩1、进入游戏-大厅左...
九分钟策略!途游游戏辅助软件,... 九分钟策略!途游游戏辅助软件,顺欣茶楼有没有辅助,系统教程(有挂细节)-哔哩哔哩1、全新机制【顺欣茶...