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

相关内容

热门资讯

透视插件!wepoker可以设... 透视插件!wepoker可以设置盖牌-关于开挂透视辅助教程(有挂教学)透视插件!wepoker可以设...
最新技巧“浙江游戏大厅修改器”... 最新技巧“浙江游戏大厅修改器”原先有开挂辅助挂(确实有挂);1、这是跨平台的浙江游戏大厅修改器黑科技...
透视挂透视!hhpoker可以... 透视挂透视!hhpoker可以开挂-揭露开挂透视辅助攻略(有挂攻略)1、hhpoker可以开挂系统规...
玩家必看分享“小程序微乐游戏辅... 玩家必看分享“小程序微乐游戏辅助器”其实有开挂辅助器(详细教程);1、让任何用户在无需AI插件第三方...
透视工具!wepoker国外版... 透视工具!wepoker国外版透视-教你开挂透视辅助工具(了解有挂)1、全新机制【wepoker国外...
专业讨论“欢乐游戏城破解版内置... 专业讨论“欢乐游戏城破解版内置修改器”本来有开挂辅助脚本(了解有挂);详细欢乐游戏城破解版内置修改器...
一分钟教你“宝宝游戏辅助”好像... 您好:宝宝游戏辅助这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特别...
透视最新!hhpoker透视挂... 透视最新!hhpoker透视挂实战视频-解谜开挂透视辅助攻略(有挂技术)1、超多福利:超高返利,海量...
9分钟了解“四川家园游戏辅助器... 9分钟了解“四川家园游戏辅助器平台交易”果然有开挂辅助下载(有挂规律);亲真的是有正版授权,小编(透...
透视科技!wepoker智能辅... 透视科技!wepoker智能辅助插件-教你开挂透视辅助插件(有挂方针)1、进入到wepoker智能辅...