Use of parcelable and serializable interfaces for data transmission between Android activities

Source: Internet
Author: User
Tags object serialization

When data is transmitted between activities, in order to avoid the trouble, some values are often encapsulated into objects, and then the entire object is passed over. The parcelable interface and the serializable interface can be implemented when an object is uploaded.

0. Two interfaces are explained:

1) the serializable interface is supported by javase itself.

2) parcelable is a unique feature of Android, which is more efficient than serializable interfaces. It is also supported for intent data transmission and can also be used for inter-process communication (IPC ), except for the basic type, only the classes that implement the parcelable interface can be put into parcel.

3) when to use serialization?

A) when you want to write the objects in the memory to the hard disk;
B) when you want to use a socket to transmit objects over the network;
C) when you want to transmit objects through RMI;

A) For example, if your memory is insufficient, the computer will temporarily save some objects in the memory to the hard disk and then read them into the memory when they are used, the storage space of the hard disk is the so-called virtual memory. For example, if you want to save a specific object to a file and I will use it several days later, you need to implement the serializable interface;
B) During Java socket programming, you may sometimes want to transmit a certain type of objects, so you also need to implement the serializable interface; the most common is that you transmit a string, it is a class in JDK and also implements the serializable interface, so it can be transmitted over the network.
C) if you want to call a method of a remote object through remote method call (RMI), such as calling the method of an object of another computer B in computer, then you need to get the reference of the target object of computer B through the JNDI service, and transfer the object from B to A, you need to implement the serialization interface.

1. What is the parcelable interface?

1) parcelable defines the interfaces for writing data to and reading data from parcel. An object (represented by a class). To encapsulate it in a message, you must implement this interface to implement this interface, this entity becomes "packable.

2) parcelable interface definition:

Public interface parcelable {// content description interface. You do not need to worry about public int describecontents (); // write the interface function and package public void writetoparcel (parcel DEST, int flags ); // read interface, which is used to construct an instance that implements parcelable from parcel. Because the implementation class is unknown here, you need to use the template method. The inherited class name is passed in through the template parameter. // To implement the input of template parameters, the Creator embedded interface is defined here, which contains two interface functions that return one and multiple inherited class instances respectively. Public interface creator <t> {public t createfromparcel (parcel source); Public T [] newarray (INT size );}}

3) How to Implement the parcelable interface?

From the parcelable interface definition, we can see that to implement the parcelable interface, we need to implement the following methods:

(1) describecontents method. Content interface description. By default, 0 is returned;

(2) writetoparcel method. This method writes the data of the class to the external provided parcel. That is, package the data to be transferred to the parcel container for storage, so that the data can be obtained from the parcel container. This method is declared as follows:

For more information about writetoparcel (parcel DEST, int flags), see the doc.

(3) Static parcelable. Creator interface. This interface has two methods:

Createfromparcel (parcel in) reads the passed data value from the parcel container and encapsulates it into a parcelable object and returns the logic layer.

Newarray (INT size) creates an array of T type and size. It can only be a single sentence (return New T [size. The method is used for external class deserialization of this class array.

4) code implementation>

(1) Implement the myparcelable class:

Package COM. jyxp. my. parcelable; import Java. util. arraylist; import Java. util. list; import android. OS. parcel; import android. OS. parcelable; public class myparcelable implements parcelable {private int minteger; private extends mparcelable; private list <strong> myparcelable2s = new arraylist <strong> (); Private myserializable mmyserializable; Public myparcelable () {// todo auto-generated constructor stub} @ suppresswarnings ("unchecked") Public myparcelable (parcel in) {// todo auto-generated constructor stubminteger = in. readint (); mparcelable = in. readparcelable (myparcelable2.class. getclassloader (); // The classloader in this region cannot be nullmyparcelable2s = in. readarraylist (myparcelable2.class. getclassloader (); mmyserializable = (myserializable) in. readserializable ();} public int getminteger () {return minteger;} public void setminteger (INT minteger) {This. minteger = minteger;} public myparcelable2 getmparcelable () {return mparcelable;} public void setmparcelable (myparcelable2 mparcelable) {This. mparcelable = mparcelable;} public list <myparcelable2> getmyparcelable2s () {return myparcelable2s;} public void setmyparcelable2s (list <myparcelable2> myparcelable2s) {This. myparcelable2s = myparcelable2s;} public myserializable getmmyserializable () {return mmyserializable;} public void setmmyserializable (myserializable mmyserializable) {This. mmyserializable = mmyserializable;} @ overridepublic int describecontents () {// todo auto-generated method stubreturn 0;} @ overridepublic void writetoparcel (parcel DEST, int flags) {// todo auto-generated method stubdest. writeint (minteger); DeST. writeparcelable (mparcelable, flags); DeST. writelist (myparcelable2s); DeST. writeserializable (mmyserializable);} public static final parcelable. creator <myparcelable> creator = new creator <myparcelable> () {@ overridepublic myparcelable [] newarray (INT size) {// todo auto-generated method stubreturn new myparcelable [size];} @ overridepublic myparcelable createfromparcel (parcel source) {// todo auto-generated method stubreturn new myparcelable (source );}};}

Note:

1. The parcelable. Creator interface must be implemented, and the access control must be public !!; The object that implements the parcelable. Creator interface must be named Creator !! Otherwise, an error is returned when you obtain the data, as shown in the following figure: Android. OS. badparcelableexception:

2. When reading data in the parcel container, the data must be read in the Order stated by the member variables. Otherwise, an error occurs when obtaining data.

3. Note that the attribute sequence corresponding to parcel out and in cannot be incorrect. Otherwise, the value cannot be obtained. If the value to be passed does not contain write or read, the value cannot be obtained.

4. The parcelable interface is implemented by finding the parcelable interface in the android API documentation. For details, see android
File, replace all the myparcelable class names with the demo copy, and then enter the write and read values. The above Code provides some examples when you fill in the value. Sometimes the following error occurs:

(1) caused by: Android. OS. badparcelableexception: classnotfoundexception when unmarshalling, because the classloader is set incorrectly or classloader is not input.

(2) Java. Lang. runtimeexception: parcelable encountered ioexception writing serializable object, because the objects in the passed parcelable object must also be parcelable or serializable.

2. What is the serializable interface?

1) An object serialization interface. A class can only implement the serializable interface, and its objects are serializable. Therefore, to serialize objects of some classes, these classes must implement the serializable interface. In fact, serializable is an empty interface with no specific content. Its purpose is simply to identify a class object that can be serialized.

2) How to Implement the serializable interface?

It's easy. You only need the implements serializable interface.

3) code implementation>

package com.jyxp.my.parcelable;import java.io.Serializable;public class MySerializable implements Serializable {private static final long serialVersionUID = 1L;private Double mDouble;private Float mFloat;public MySerializable() {// TODO Auto-generated constructor stub}public Double getmDouble() {return mDouble;}public void setmDouble(Double mDouble) {this.mDouble = mDouble;}public Float getmFloat() {return mFloat;}public void setmFloat(Float mFloat) {this.mFloat = mFloat;}}

3. How to transmit values

1) Basic data types. You can

2) When the serializable object is passed, the custom member object (non-API serializable object) in the passed serializable object must also implement the serializable interface. Otherwise, caused may occur.
By: Java. Io. notserializableexception exception. From the code above, we can see that the serializable object can be passed in the parcelable object, but can there be parcelable when it is passed in the serializable object? The answer is no. java. Io. notserializableexception will occur.

3) The Android API can only pass the set of parcelable objects, but not the set of serializable objects, that is, it can only pass the arraylist <bitmap>, but not the arraylist <designer>. When I first started learning Android, all objects were encapsulated into serializable and then passed. Because serializable is a localized interface in javase, I am very familiar with it. At that time, I was wondering why there was a parcelable interface, what are the differences between the two? Later, when the serializable cannot meet the requirements, it will be clear that android uses pacelable to encapsulate its own things, just like bitmap in worker, and classloader does not need to be set during read.

4) The Enum can also be passed. You just need to use the enum as a class.


4. instance code>

Portal >>>>

For more information, see http://blog.csdn.net/js931178805/article/details/8268144thank you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.