Android常用的2种对象序列化

Parcelable

安卓传递对象,要求对象序列化, 安卓提供2种序列化接口:

  1. Serializable
  2. Parcelable

Parcelable 接口来序列化,是Android提供的一个比Serializable 效率更高的序列化类。

实现序列化

Parcelable需要实现三个函数

  1. void writeToParcel(Parcel dest, int flags)将需要序列化存储的数据写入外部提供的Parcel对象dest。读取Parcel数据的次序要和这里的write次序一致,否则可能会读错数据。
  2. describeContents()描述,直接返回0即可。
  3. static final Parcelable.Creator对象CREATOR这个CREATOR命名是固定的,而它对应的接口有两个方法:createFromParcel(Parcel source) 实现从source创建出JavaBean实例的功能。

newArray(int size) 创建一个类型为T,长度为size的数组,仅一句话(return new T[size])即可。估计本方法是供外部类反序列化本类数组使用。

public class Chat implements Parcelable{

	private int sourceId;
	private String name,content,time,nameFrom;
	private int mode,count;
	public Chat() {
		// TODO Auto-generated constructor stub
	}
	//该静态域是必须要有的,而且名字必须是CREATOR,否则会出错
	public static final Creator<Chat> CREATOR = new Creator<Chat>() {

		@Override
		public Chat createFromParcel(Parcel source) {
			//从Parcel读取通过writeToParcel方法写入的Chat的相关成员信息
			Chat chat = new Chat();
			chat.content = source.readString();
			chat.time = source.readString();
			chat.nameFrom = source.readString();
			chat.mode = source.readInt();
			chat.name = source.readString();
			//更加读取到的信息,创建返回对象
			return chat;
		}

		@Override
		public Chat[] newArray(int size) {
			// TODO Auto-generated method stub
			 //返回Chat对象数组
			return new Chat[size];
		}
	};

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}
	//实现Parcel接口必须覆盖实现的方法
	@Override
	public void writeToParcel(Parcel dest, int flags) {
		/*将Chat的成员写入Parcel,
         * 注:Parcel中的数据是按顺序写入和读取的,即先被写入的就会先被读取出来
         */
		dest.writeString(this.content);
		dest.writeString(this.time);
		dest.writeString(this.nameFrom);
		dest.writeInt(this.mode);
		dest.writeString(this.name);
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值