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

相关内容

热门资讯

开挂辅助软件"wep... 开挂辅助软件"wepoker开辅助能查到吗"开挂(透视)辅助下载(有挂透视);wepoker开辅助能...
开挂辅助下载"wpk... 开挂辅助下载"wpk俱乐部是真的吗"开挂(透视)辅助脚本(确实有挂) 【无需打开直接搜索加薇1367...
开挂辅助下载"pok... 开挂辅助下载"pokemmo辅助器"开挂(透视)辅助下载(竟然有挂);无需打开直接搜索加薇13670...
开挂辅助平台"德州局... 开挂辅助平台"德州局怎么透视"开挂(透视)辅助脚本(有挂头条)您好:德州局怎么透视这款游戏可以开挂,...
开挂辅助安装"德普之... 大家好,今天小编来为大家解答德普之星透视辅助这个问题咨询软件客服可以免费测试直接加微信(136704...
开挂辅助安装"hhp... hhpoker软件可以玩吗开挂教程视频分享装挂详细步骤在当今的网络游戏中,hhpoker软件可以玩吗...
开挂辅助脚本"wep... wepoker轻量版辅助 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理...
开挂辅助插件"hh ... hh poker软件开挂教程视频分享装挂详细步骤在当今的网络游戏中,hh poker软件作为一种经典...
开挂辅助脚本"aap... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
开挂辅助安装"wep... 开挂辅助安装"wepoker有透视功能吗"开挂(透视)辅助插件(有挂存在) 了解更多开挂安装加(13...