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

使用Parcelable步骤:

1.实现Parcelable接口

2.实现接口中的两个方法

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

第一个方法是内容接口描述,默认返回0就可以了

第二个方法是将我们的对象序列化一个Parcel对象,也就是将我们的对象存入Parcel中

3.实例化静态内部对象CREATOR实现接口Parcelable.Creator,实例化CREATOR时要实现其中的两个方法,其中createFromParcel的功能就是从Parcel中读取我们的对象。

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

看一个代码示例:

  1. public class Person implements Parcelable{
  2. private String username;
  3. private String nickname;
  4. private int age;
  5. public String getUsername() {
  6. return username;
  7. }
  8. public void setUsername(String username) {
  9. this.username = username;
  10. }
  11. public String getNickname() {
  12. return nickname;
  13. }
  14. public void setNickname(String nickname) {
  15. this.nickname = nickname;
  16. }
  17. public int getAge() {
  18. return age;
  19. }
  20. public void setAge(int age) {
  21. this.age = age;
  22. }
  23. public Person(String username, String nickname, int age) {
  24. super();
  25. this.username = username;
  26. this.nickname = nickname;
  27. this.age = age;
  28. }
  29. public Person() {
  30. super();
  31. }
  32. /**
  33. * 这里的读的顺序必须与writeToParcel(Parcel dest, int flags)方法中
  34. * 写的顺序一致,否则数据会有差错,比如你的读取顺序如果是:
  35. * nickname = source.readString();
  36. * username=source.readString();
  37. * age = source.readInt();
  38. * 即调换了username和nickname的读取顺序,那么你会发现你拿到的username是nickname的数据,
  39. * 而你拿到的nickname是username的数据
  40. * @param source
  41. */
  42. public Person(Parcel source) {
  43. username = source.readString();
  44. nickname=source.readString();
  45. age = source.readInt();
  46. }
  47. /**
  48. * 这里默认返回0即可
  49. */
  50. @Override
  51. public int describeContents() {
  52. return 0;
  53. }
  54. /**
  55. * 把值写入Parcel中
  56. */
  57. @Override
  58. public void writeToParcel(Parcel dest, int flags) {
  59. dest.writeString(username);
  60. dest.writeString(nickname);
  61. dest.writeInt(age);
  62. }
  63. public static final Creator<Person> CREATOR = new Creator<Person>() {
  64. /**
  65. * 供外部类反序列化本类数组使用
  66. */
  67. @Override
  68. public Person[] newArray(int size) {
  69. return new Person[size];
  70. }
  71. /**
  72. * 从Parcel中读取数据
  73. */
  74. @Override
  75. public Person createFromParcel(Parcel source) {
  76. return new Person(source);
  77. }
  78. };
  79. }

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

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

  1. /*
  2. * Copyright (C) 2006 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package android.os;
  17. /**
  18. * Interface for classes whose instances can be written to
  19. * and restored from a {@link Parcel}. Classes implementing the Parcelable
  20. * interface must also have a static field called <code>CREATOR</code>, which
  21. * is an object implementing the {@link Parcelable.Creator Parcelable.Creator}
  22. * interface.
  23. *
  24. * <p>A typical implementation of Parcelable is:</p>
  25. *
  26. * <pre>
  27. * public class MyParcelable implements Parcelable {
  28. * private int mData;
  29. *
  30. * public int describeContents() {
  31. * return 0;
  32. * }
  33. *
  34. * public void writeToParcel(Parcel out, int flags) {
  35. * out.writeInt(mData);
  36. * }
  37. *
  38. * public static final Parcelable.Creator&lt;MyParcelable&gt; CREATOR
  39. * = new Parcelable.Creator&lt;MyParcelable&gt;() {
  40. * public MyParcelable createFromParcel(Parcel in) {
  41. * return new MyParcelable(in);
  42. * }
  43. *
  44. * public MyParcelable[] newArray(int size) {
  45. * return new MyParcelable[size];
  46. * }
  47. * };
  48. *
  49. * private MyParcelable(Parcel in) {
  50. * mData = in.readInt();
  51. * }
  52. * }</pre>
  53. */
  54. public interface Parcelable {
  55. /**
  56. * Flag for use with {@link #writeToParcel}: the object being written
  57. * is a return value, that is the result of a function such as
  58. * "<code>Parcelable someFunction()</code>",
  59. * "<code>void someFunction(out Parcelable)</code>", or
  60. * "<code>void someFunction(inout Parcelable)</code>". Some implementations
  61. * may want to release resources at this point.
  62. */
  63. public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;
  64. /**
  65. * Bit masks for use with {@link #describeContents}: each bit represents a
  66. * kind of object considered to have potential special significance when
  67. * marshalled.
  68. */
  69. public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;
  70. /**
  71. * Describe the kinds of special objects contained in this Parcelable's
  72. * marshalled representation.
  73. *
  74. * @return a bitmask indicating the set of special object types marshalled
  75. * by the Parcelable.
  76. */
  77. public int describeContents();
  78. /**
  79. * Flatten this object in to a Parcel.
  80. *
  81. * @param dest The Parcel in which the object should be written.
  82. * @param flags Additional flags about how the object should be written.
  83. * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
  84. */
  85. public void writeToParcel(Parcel dest, int flags);
  86. /**
  87. * Interface that must be implemented and provided as a public CREATOR
  88. * field that generates instances of your Parcelable class from a Parcel.
  89. */
  90. public interface Creator<T> {
  91. /**
  92. * Create a new instance of the Parcelable class, instantiating it
  93. * from the given Parcel whose data had previously been written by
  94. * {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.
  95. *
  96. * @param source The Parcel to read the object's data from.
  97. * @return Returns a new instance of the Parcelable class.
  98. */
  99. public T createFromParcel(Parcel source);
  100. /**
  101. * Create a new array of the Parcelable class.
  102. *
  103. * @param size Size of the array.
  104. * @return Returns an array of the Parcelable class, with every entry
  105. * initialized to null.
  106. */
  107. public T[] newArray(int size);
  108. }
  109. /**
  110. * Specialization of {@link Creator} that allows you to receive the
  111. * ClassLoader the object is being created in.
  112. */
  113. public interface ClassLoaderCreator<T> extends Creator<T> {
  114. /**
  115. * Create a new instance of the Parcelable class, instantiating it
  116. * from the given Parcel whose data had previously been written by
  117. * {@link Parcelable#writeToParcel Parcelable.writeToParcel()} and
  118. * using the given ClassLoader.
  119. *
  120. * @param source The Parcel to read the object's data from.
  121. * @param loader The ClassLoader that this object is being created in.
  122. * @return Returns a new instance of the Parcelable class.
  123. */
  124. public T createFromParcel(Parcel source, ClassLoader loader);
  125. }
  126. }

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

android开发之Parcelable使用详解的更多相关文章

  1. [置顶] Android开发之MediaPlayerService服务详解(一)

    前面一节我们分析了Binder通信相关的两个重要类:ProcessState 和 IPCThreadState.ProcessState负责打开Binder 驱动,每个进程只有一个.而 IPCThre ...

  2. Android开发之EditText属性详解

    1.EditText输入的文字为密码形式的设置 (1)通过.xml里设置: 把该EditText设为:android:password="true" // 以”.”形式显示文本 ( ...

  3. 【转】 Android开发之EditText属性详解

    原文网址:http://blog.csdn.net/qq435757399/article/details/7947862 1.EditText输入的文字为密码形式的设置 (1)通过.xml里设置: ...

  4. android开发之onCreate( )方法详解

    这里我们只关注一句话:This is where you should do all of your normal static set up.其中我们只关注normal static,normal: ...

  5. Android开发之MediaRecorder类详解

    MediaRecorder类介绍: MediaRecorder类是Android sdk提供的一个专门用于音视频录制,一般利用手机麦克风采集音频,摄像头采集图片信息. MediaRecorder主要函 ...

  6. android开发之PreferenceScreen使用详解

    是在惭愧,学习android也有一段时间了,今天才是第一次接触PreferenceScreen.记录下来,与大家分享. 本文参考:http://lovezhou.iteye.com/blog/1020 ...

  7. Android开发之SoundPool使用详解

    使用SoundPool播放音效 如果应用程序经常播放密集.急促而又短暂的音效(如游戏音效)那么使用MediaPlayer显得有些不太适合了.因为MediaPlayer存在如下缺点: 1) 延时时间较长 ...

  8. NDK开发之JNIEnv参数详解

    即使我们Java层的函数没有参数,原生方法还是自带了两个参数,其中第一个参数就是JNIEnv. 如下: native方法: public native String stringFromC(); pu ...

  9. NDK开发之ndk-build命令详解

    毫无疑问,通过执行ndk-build脚本启动android ndk构建系统. 默认情况下,ndk-build脚本在工程的主目录中执行,如: 我们可以用使用-C参数改变上述行为,-C指定工程的目录,这样 ...

随机推荐

  1. linux 监控

    http://www.iyunv.com/thread-50606-1-1.html http://segmentfault.com/a/1190000002537665 http://blog.cs ...

  2. Performance Test of List<T>, LinkedList<T>, Queue<T>, ConcurrentQueue<T>

    //Test Group 1 { var watch = Stopwatch.StartNew(); var list = new List<int>(); ; j < ; j++) ...

  3. OA学习笔记-006-SPRING2.5与hibernate3.5整合

    一.为什么要整合 1,管理SessionFactory实例(只需要一个) 2,声明式事务管理 spirng的作用 IOC 管理对象.. AOP 事务管理.. 二.整合步骤 1.整合sessionFac ...

  4. Linux本地无法登录,远程却可以登录

    [root@oraserver ~]# vi /etc/pam.d/login 将以下内容注释掉: #session    required     /lib/security/pam_limits. ...

  5. 【canvas】伸缩 / 剪裁 / 文本 / 阴影 / 填充图案 / 填充渐变

    <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8& ...

  6. [转]NHibernate之旅(2):第一个NHibernate程序

    本节内容 开始使用NHibernate 1.获取NHibernate 2.建立数据库表 3.创建C#类库项目 4.设计Domain 4-1.设计持久化类 4-2.编写映射文件 5.数据访问层 5-1. ...

  7. 常用开源GIS项目

    常用开源GIS项目     常用开源桌面GIS软件 QGIS 始于2002年5月,算得上是开源GIS平台中的后起之秀.界面友好,分析功能可与GRASS GIS相媲美.主页:http://www.qgi ...

  8. HDOJ/HDU 1029 Ignatius and the Princess IV(简单DP,排序)

    此题无法用JavaAC,不相信的可以去HD1029题试下! Problem Description "OK, you are not too bad, em- But you can nev ...

  9. uploadify上传图片(限制最多五张)

    项目中遇到图片上传的情况,好多都是使用服务器上传控件进行上传的,很是不爽. 然后在网上找到了uploadify的方法,自己总结和修改后分享给大家. 项目文档预览: 1.引用原有css和js    &l ...

  10. 在MyEclipse配置自己安装的Tomcat(2014.08.18)

    今天因为要在tomcat下运行一个java项目,第一次嘛,遇到了不少问题,总结分享一下: 第一次,我直接将 MyEclipse 生成的项目放到 tomcat 安装目录的 webapps 目录下,运行出 ...