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

相关内容

热门资讯

外挂策略!来玩app 德州 辅... 外挂策略!来玩app 德州 辅助,werplan辅助软件-本来一直总是有辅助方法(哔哩哔哩)1、游戏...
外挂总结!xpoker辅助,w... 外挂总结!xpoker辅助,werplan免费挂下载-果然真的有辅助攻略(哔哩哔哩)1、该软件可以轻...
外挂总结!智星菠萝德州辅助译码... 外挂总结!智星菠萝德州辅助译码插件靠谱吗,智星菠萝辅助-都是是有辅助方法(哔哩哔哩)1、这是跨平台的...
外挂窍门!红龙poker辅助,... 外挂窍门!红龙poker辅助,德州来玩辅助器-一贯一直都是有辅助工具(哔哩哔哩)1、德州来玩辅助器脚...
外挂手筋!佛手在线大菠萝智能辅... 外挂手筋!佛手在线大菠萝智能辅助器,pokerworld修改器-总是真的是有辅助神器(哔哩哔哩)一、...
外挂手册!拱趴大菠萝万能挂,a... 外挂手册!拱趴大菠萝万能挂,agpoker辅助-竟然一直都是有辅助教程(哔哩哔哩)1、拱趴大菠萝万能...
外挂手筋!werplan怎么透... 外挂手筋!werplan怎么透视,哈糖大菠萝有挂吗-果然有辅助技巧(哔哩哔哩)1、下载好哈糖大菠萝有...
外挂窍要!德普之星透视辅助软件... 外挂窍要!德普之星透视辅助软件激活码,约局吧德州真的存在透视吗-真是一直总是有辅助教程(哔哩哔哩)1...
外挂模块!newpoker脚本... 外挂模块!newpoker脚本,xpoker辅助器-原来一直总是有辅助教程(哔哩哔哩)xpoker辅...
外挂指引!德普之星透视辅助软件... 外挂指引!德普之星透视辅助软件下载,智星菠萝有挂吗-本来一直总是有辅助工具(哔哩哔哩)1、用户打开应...