当前位置: 首页 > 编程日记 > 正文

android开发之Parcelable使用详解

想要在两个activity之间传递对象,那么这个对象必须序列化,android中序列化一个对象有两种方式,一种是实现Serializable接口,这个非常简单,只需要声明一下就可以了,不痛不痒。但是android中还有一种特有的序列化方法,那就是实现Parcelable接口,使用这种方式来序列化的效率要高于实现Serializable接口。不过Serializable接口实在是太方便了,因此在某些情况下实现这个接口还是非常不错的选择。
使用Parcelable步骤:
1.实现Parcelable接口
2.实现接口中的两个方法

public int describeContents();
public void writeToParcel(Parcel dest, int flags);

第一个方法是内容接口描述,默认返回0就可以了
第二个方法是将我们的对象序列化一个Parcel对象,也就是将我们的对象存入Parcel中
3.实例化静态内部对象CREATOR实现接口Parcelable.Creator,实例化CREATOR时要实现其中的两个方法,其中createFromParcel的功能就是从Parcel中读取我们的对象。

也就是说我们先利用writeToParcel方法写入对象,再利用createFromParcel方法读取对象,因此这两个方法中的读写顺序必须一致,否则会出现数据紊乱,一会我会举例子。
看一个代码示例:

public class Person implements Parcelable{private String username;private String nickname;private int age;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getNickname() {return nickname;}public void setNickname(String nickname) {this.nickname = nickname;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Person(String username, String nickname, int age) {super();this.username = username;this.nickname = nickname;this.age = age;}public Person() {super();}/*** 这里的读的顺序必须与writeToParcel(Parcel dest, int flags)方法中* 写的顺序一致,否则数据会有差错,比如你的读取顺序如果是:* nickname = source.readString();* username=source.readString();* age = source.readInt();* 即调换了username和nickname的读取顺序,那么你会发现你拿到的username是nickname的数据,* 而你拿到的nickname是username的数据* @param source*/public Person(Parcel source) {username = source.readString();nickname=source.readString();age = source.readInt();}/*** 这里默认返回0即可*/@Overridepublic int describeContents() {return 0;}/*** 把值写入Parcel中*/@Overridepublic void writeToParcel(Parcel dest, int flags) {dest.writeString(username);dest.writeString(nickname);dest.writeInt(age);}public static final Creator<Person> CREATOR = new Creator<Person>() {/*** 供外部类反序列化本类数组使用*/@Overridepublic Person[] newArray(int size) {return new Person[size];}/*** 从Parcel中读取数据*/@Overridepublic Person createFromParcel(Parcel source) {return new Person(source);}};
}

本工程源码http://pan.baidu.com/s/1hqzY3go

最后贴上Parcelable源码,Google已经给了一个示例了:

/** Copyright (C) 2006 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package android.os;/*** Interface for classes whose instances can be written to* and restored from a {@link Parcel}.  Classes implementing the Parcelable* interface must also have a static field called <code>CREATOR</code>, which* is an object implementing the {@link Parcelable.Creator Parcelable.Creator}* interface.* * <p>A typical implementation of Parcelable is:</p>* * <pre>* public class MyParcelable implements Parcelable {*     private int mData;**     public int describeContents() {*         return 0;*     }**     public void writeToParcel(Parcel out, int flags) {*         out.writeInt(mData);*     }**     public static final Parcelable.Creator&lt;MyParcelable&gt; CREATOR*             = new Parcelable.Creator&lt;MyParcelable&gt;() {*         public MyParcelable createFromParcel(Parcel in) {*             return new MyParcelable(in);*         }**         public MyParcelable[] newArray(int size) {*             return new MyParcelable[size];*         }*     };*     *     private MyParcelable(Parcel in) {*         mData = in.readInt();*     }* }</pre>*/
public interface Parcelable {/*** Flag for use with {@link #writeToParcel}: the object being written* is a return value, that is the result of a function such as* "<code>Parcelable someFunction()</code>",* "<code>void someFunction(out Parcelable)</code>", or* "<code>void someFunction(inout Parcelable)</code>".  Some implementations* may want to release resources at this point.*/public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;/*** Bit masks for use with {@link #describeContents}: each bit represents a* kind of object considered to have potential special significance when* marshalled.*/public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;/*** Describe the kinds of special objects contained in this Parcelable's* marshalled representation.*  * @return a bitmask indicating the set of special object types marshalled* by the Parcelable.*/public int describeContents();/*** Flatten this object in to a Parcel.* * @param dest The Parcel in which the object should be written.* @param flags Additional flags about how the object should be written.* May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.*/public void writeToParcel(Parcel dest, int flags);/*** Interface that must be implemented and provided as a public CREATOR* field that generates instances of your Parcelable class from a Parcel.*/public interface Creator<T> {/*** Create a new instance of the Parcelable class, instantiating it* from the given Parcel whose data had previously been written by* {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.* * @param source The Parcel to read the object's data from.* @return Returns a new instance of the Parcelable class.*/public T createFromParcel(Parcel source);/*** Create a new array of the Parcelable class.* * @param size Size of the array.* @return Returns an array of the Parcelable class, with every entry* initialized to null.*/public T[] newArray(int size);}/*** Specialization of {@link Creator} that allows you to receive the* ClassLoader the object is being created in.*/public interface ClassLoaderCreator<T> extends Creator<T> {/*** Create a new instance of the Parcelable class, instantiating it* from the given Parcel whose data had previously been written by* {@link Parcelable#writeToParcel Parcelable.writeToParcel()} and* using the given ClassLoader.** @param source The Parcel to read the object's data from.* @param loader The ClassLoader that this object is being created in.* @return Returns a new instance of the Parcelable class.*/public T createFromParcel(Parcel source, ClassLoader loader);}
}

版权声明:本文为博主原创文章,未经博主允许不得转载。若有错误地方,还望批评指正,不胜感激。

转载于:https://www.cnblogs.com/lenve/p/4770532.html

相关文章:

tomcat mysql 中文乱码_tomcat 中文乱码, mysql 中文乱码_MySQL

Tomcattomcat中文乱码 get 请求.修改server.xml中的添加URIEncodingUTF-8tomcat中文乱码 post 版另外HttpURLConnection上传参数的时候要转码成url编码 outStream.writeBytes("&" URLEncoder.encode(key, "utf-8") "" URLEncoder.encode(…

自己写的Python数据库连接类和sql语句拼接方法

这个工具类十分简单和简洁。 sql拼接方法 # encodingutf-8 from django.http import HttpResponse from anyjson import serialize from django.http import HttpResponse from anyjson import serialize import MySQLdbdef safe(s):return MySQLdb.escape_string(s)def get_i_…

Koa 本地搭建 HTTPS 环境

openssl 首先本地需要安装 openssl&#xff0c;用于生成自签名证书。 $ brew install openssl检查安装&#xff1a; $ openssl version LibreSSL 2.6.5生成证书 执行以下命令生成证书&#xff1a; openssl req -nodes -new -x509 -keyout server.key -out server.cert Generati…

eDRX中的Paging

在idle下&#xff0c;Legacy LTE的DRX周期最大值为2.56s, 频繁的唤醒会消耗UE的电量。为了降低功耗&#xff0c;延长待机时间&#xff0c;在Release 13&#xff0c;NB-IOT引入eDRX模式。eDRX就是Extended idle-mode DRX cycle,扩展不连续接受。 下面介绍超帧(Hyper-SFN)的概念…

ios 图片自动轮播

ios 图片自动轮播 #import "NYViewController.h"#define kImageCount 5interface NYViewController () <UIScrollViewDelegate> property (nonatomic, strong) UIScrollView *scrollView; property (nonatomic, strong) UIPageControl *pageControl;property (…

mysql练习题及答案_MySQL经典练习题及答案,常用SQL语句练习50题

#--插入学生表测试数据#(01 , 赵雷 , 1990-01-01 , 男)insert into Student values(01 , 赵雷 , 1990-01-01 , 男);insert into Student values(02 , 钱电 , 1990-12-21 , 男);insert into Student values(03 , 孙风 , 1990-05-20 , 男);insert into Student values(04 , 李云 …

一次因NAS存储故障引起的Linux系统恢复案例

推荐&#xff1a;10年技术力作&#xff1a;《高性能Linux服务器构建实战Ⅱ》全网发行&#xff0c;附试读章节和全书实例源码下载&#xff01;一、故障现象描述NAS操作系统内核为Linux&#xff0c;自带的存储有16块硬盘&#xff0c;总共分两组&#xff0c;每组做了RAID5&#xf…

手机网页H5 自适应不同分辨率的屏幕 必学标签meta之viewport

viewport 语法介绍 <meta name"viewport"content" height [pixel_value | device-height] , width [pixel_value | device-width ] , initial-scale float_value , minimum-scale float_value , maximum-scale float_value , user-scalable [yes | no]…

PSM-省电模式(PowerSaving Mode)

PSM: PowerSaving Mode, 省电模式, 是R12引入的新feature, spec可以参考&#xff1a;3GPP 24.301-5.3.11 Powersaving mode 和 23.682-4.5.4 UEPower Saving Mode.在PSM模式下&#xff0c;网络无法到达UE&#xff0c;UE无法接受来自于网络的数据和请求&#xff0c;类似于关机&…

mysql keepalived低版本_Mysql+keepalived主主切换

Mysqlkeepalived主主切换一&#xff0c;环境介绍网络结构&#xff1a;VIP :192.168.1.30MYSQL A:192.168.1.21MYSQL B:192.168.1.22二、mysql主主同步要实现mysqlkeepalived主主切换&#xff0c;首先要实现的就是两台mysql服务器的主主同步&#xff0c;查看http://smalldeng.bl…

Android环境搭建和Android HelloWorld—Android开发环境搭建

Android_Android开发环境搭建-搭建Android的开发环境 1.我考虑先下载JDK7.0,在JDK的安装中&#xff0c;考虑一般SDK都是向上兼容的&#xff0c;于是选择了最高的版本7.0这里是我总结的详细的JDK配置以及路径配置的过程&#xff1a; JavaSDK安装&#xff1a;安装JDK.exe然后配置…

30个在线学习设计与开发的站点

转&#xff1a;http://www.w3cschool.cc/w3cnote/30-best-websites-to-learn.html

【07月01日】A股滚动市净率PB历史新低排名

2010年01月01日 到 2019年07月01日 之间&#xff0c;滚动市净率历史新低排名。 上市三年以上的公司&#xff0c;2019年07月01日市净率在30以下的公司。 来源&#xff1a;A股滚动市净率(PB)历史新低排名。 1 - XD中国石(SH601857) - 历史新低 - PB_TTM&#xff1a;1.03 - PE_TTM…

LTE-连接态下的DRX

C-DRX: Connectedmode DRX,连接态下的DRX UE在连接态下&#xff0c;如果没有数据传输的话&#xff0c;会根据DRX的规则停止监听PDCCH(监听PDCCH可参考&#xff1a;PDCCH),从而达到省电的目的。一个DRX周期包含On Duration 和Opportunity for DRX 两个时间段。3GPP - 36.321中示…

mvc mvp mvvm的区别与联系_MVC,MVP,MVVM比较以及区别(上)

MVC&#xff0c;MVP&#xff0c;MVVM都是用来解决界面呈现和逻辑代码分离而出现的模式&#xff0c;以前只是对他们有部分的了解&#xff0c;没有深入的研究过&#xff0c;对于一些里边的概念和区别也是一知半解。现在一边查资料&#xff0c;并结合自己的理解&#xff0c;来谈一…

【性格心理学】为什么我在关键时刻总是紧张?

为什么我在关键时刻总是紧张&#xff1f; ~这是一种“对人恐惧症”&#xff0c;因为害怕失败~ 当在众人面前讲话时&#xff0c;或者公司会议中轮到自己发言时&#xff0c;有的人就会大汗淋漓、面红耳赤&#xff0c;甚至心跳不已&#xff0c;结结巴巴地连话都说不出来。在重大场…

iOS图片模糊效果

增加 CoreImage.framework CoreGraphic.framework 等库 在使用时引入&#xff1a;#import <Accelerate/Accelerate.h> &#xff0c;支持iOS 5.0 及以上。 -(void)show { UIImage* img [self getBlurImage:[UIImage imageNamed:"Default-568h.png"]]; [_bgIm…

YOLOv7-Pose 姿态估计-环境搭建和推理

终端,进入base环境,创建新环境,我这里创建的是p38t17(python3.8,pytorch1.7)安装pytorch:(网络环境比较差时,耗时会比较长)下载好后打开yolov7-pose源码包。imgpath:需要预测的图片的存放路径。modelpath:模型的存放路径。Yolov7-pose权重下载。打开工程后,进入设置。

分治——最近点对问题 hdu1007

问题描述 n个点在公共空间中&#xff0c;求出所有点对的欧几里得距离最小的点对。 解法1&#xff1a; 很明显的&#xff0c;暴力解决是$O(N^2)$ 解法2&#xff1a; 利用分治的思想&#xff0c;我们可以把算法优化到$O(nlogn*logn)$&#xff0c;甚至$O(nlogn)$ 我们先对所有的点…

NBIOT-NPSS/NSS/NPBCH的资源位置

1.NPSSNarrowbandPrimary Synchronization Signal时域位置每1个SFN存在一个NPSSSFNSubframeSymbol长度每个SFN5最后11个symbol11个symbols频域位置NB-IOT下行带宽固定180kHz&#xff0c;一个PRB&#xff0c;12个子载波。NPSS信号占用11个子载波2.NSSSNarrowbandSecondary Synch…

数组的排序与查找

/**对如下一个数组int[] iarr{34,67,1,56,32,78,12,45,79,4,57,102,123,3};进行排序(采用自己擅长的排序算法)&#xff0c;然后查询排序之后的采用二分查找*法查找45在在数组的索引值 &#xff0c;排序、查找封装成方法&#xff0c;然后在main方法中调用测试。*/ public class …

0基础学好python难不难_零基础学习Python难不难?Python有什么优势?

原标题&#xff1a;零基础学习Python难不难&#xff1f;Python有什么优势&#xff1f;Python是一种计算机程序设计语言。首先&#xff0c;我们普及一下编程语言的基础知识。用任何编程语言来开发程序&#xff0c;都是为了让计算机干活&#xff0c;比如下载一个MP3&#xff0c;编…

浅谈 MySQL 子查询及其优化

2019独角兽企业重金招聘Python工程师标准>>> 使用过oracle或者其他关系数据库的DBA或者开发人员都有这样的经验&#xff0c;在子查询上都认为数据库已经做过优化&#xff0c;能够很好的选择驱动表执行&#xff0c;然后在把该经验移植到mysql数据库上&#xff0c;但是…

[PHP] JQuery+Layer实现添加删除自定义标签代码

JQueryLayer实现添加删除自定义标签代码 实现效果如下&#xff1a; 实现代码如下&#xff1a; <!doctype html> <html> <head> <meta charset"utf-8"> <title>实用的文章自定义标签</title> <link rel"stylesheet"…

NB-IOT: Anchor Carrier 锚点载波

Anchor Carrier定义&#xff1a; Anchor carrier:in NB-IoT, a carrier where the UE assumes that NPSS/NSSS/NPBCH/SIB-NB are transmitted. Anchor carrier用以发送NPSS/NSSS/NPBCH/SIB-NB&#xff0c; 另外寻呼消息和随机接入过程也只能在AnchorCarrier上进行。 在使用I…

mysql8 my 010457_分享一下我在mysql5.6+mysql8数据库安装过程中的一些坑!

Mysql5.6安装下载好安装包后&#xff0c;在bin目录下用cmd打开&#xff0c;输入mysqld install 【服务名】新建个服务在windowsr输入services.msc即可查看服务怎样使用mysql在本地电脑上安装好mysql服务器后&#xff0c;使用命令开启mysql服务&#xff0c;命令为net start mysq…

14年12月CCF真题1-门禁系统

问题描述 涛涛最近要负责图书馆的管理工作,需要记录下每天读者的到访情况。每 位读者有一个编号,每条记录用读者的编号来表示。给出读者的来访记录,请 问每一条记录中的读者是第几次出现。 输入格式 输入的第一行包含一个整数n,表示涛涛的记录条数。 第二行包含n个整数,依次表…

[Oracle] - 性能优化工具(5) - AWRSQL

在AWR中定位到问题SQL语句后想要了解该SQL statement的详细运行计划&#xff0c;于是就用AWR报告中得到的SQL ID去V$SQL等几个动态性能视图中查询&#xff0c;但发现V$SQL或V$SQL_PLAN视图都已经找不到相应SQL ID的记录&#xff0c;一般来说这些语句已经从shared pool共享池中被…

三种基本排序的实现及其效率对比:冒泡排序、选择排序和插入排序

1 public class ThreeTypesOfBaseSort {2 // 三种基本排序的效率对比 3 public static void main(String[] args) {4 ThreeTypesOfBaseSort sort new ThreeTypesOfBaseSort();5 6 // 测试百万级别的数组排序&#xff0c;看三种基本排序的的效率差…

NB-IOT UE的小区接入过程

NB-IOT UE的小区接入过程如下&#xff1a;NPSS/NSSS/NPBCH的时频资源&#xff0c;可以参考&#xff1a;点击打开链接 下面详细介绍一下MIB-NB/SIB1-NB的获取过程。 MIB-NB传输 在sharetechnote中有详细的描述&#xff0c;如下&#xff1a; MIB-NB分成8个等长的可以独立编码的子…