对象系列化两种方法Serializable和Parcelable

2015-08-20 19:04 评论 0 条

在Android的Intent中传递实体的时候,需要对对象进行序列化,然后通过Bundle的putSerializable()、getSerializable()或者putParcelable()、getParcelable()方法实体存储和取出,方便我们在两个不同Activity之间传递实体,下面分别进行介绍:

1、创建实体Computer,使用Serializable序列化

public class Computer implements Serializable {
private static final long serialVersionUID = -7060210544600464481L;
private String name;
private String color;
private float price;

public String getName() {
return name;
}

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

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public float getPrice() {
return price;
}

public void setPrice(float price) {
this.price = price;
}

public static long getSerialversionuid() {
return serialVersionUID;
}

}

 

2、创建实体Phone,实现Parcelable进行序列化,如下:

public class Phone implements Parcelable {
private String phoneName;// 定义手机的品牌
private float phonePrice;// 手机的价格
private float sdkVersion;// 手机系统版本

public String getName() {
return phoneName;
}

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

public float getPrice() {
return phonePrice;
}

public void setPrice(float price) {
this.phonePrice = price;
}

public float getSdkVersion() {
return sdkVersion;
}

public void setSdkVersion(float sdkVersion) {
this.sdkVersion = sdkVersion;
}

@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(phoneName);
dest.writeFloat(phonePrice);
dest.writeFloat(sdkVersion);
}

public static final Parcelable.Creator<Phone> CREATOR = new Creator<Phone>() {

@Override
public Phone createFromParcel(Parcel source) {
Phone phone=new Phone();
phone.phoneName=source.readString();
phone.phonePrice=source.readFloat();
phone.sdkVersion=source.readFloat();
return phone;
}

@Override
public Phone[] newArray(int size) {
// TODO Auto-generated method stub
return new Phone[size];
}
};
}

3、将序列化后的对象通过Intent传递,创建MainActivity和NextActivity,如下

 

当前文章价值7.37元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

你可能感兴趣的文章

来源:每日教程每日一例,深入学习实用技术教程,关注公众号TeachCourse
转载请注明出处: https://www.teachcourse.cn/350.html ,谢谢支持!

资源分享

Android语言kotlin基本语法介绍和示例说明 Android语言kotlin基本语法介绍
ubuntu木马病毒清理 ubuntu木马病毒清理
生活杂谈之网站SEO优化方法-卢松松外链工具 生活杂谈之网站SEO优化方法-卢
浅谈短信服务SMS 浅谈短信服务SMS

发表评论

呲牙 憨笑 坏笑 偷笑 色 微笑 抓狂 睡觉 酷 流汗 鼓掌 大哭 可怜 疑问 晕 惊讶 得意 尴尬 发怒 奋斗 衰 骷髅 啤酒 吃饭 礼物 强 弱 握手 OK NO 勾引 拳头 差劲 爱你

表情