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.
Public int describeContents ();
// Write interface function, 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 MyParcelable2 mParcelable;
Private List <MyParcelable2> myParcelable2s = new ArrayList <MyParcelable2> ();
Private MySerializable mMySerializable;
 
Public MyParcelable (){
// TODO Auto-generated constructor stub
}
 
@ SuppressWarnings ("unchecked ")
Public MyParcelable (Parcel in ){
// TODO Auto-generated constructor stub
MInteger = in. readInt ();
MParcelable = in. readParcelable (MyParcelable2.class. getClassLoader (); // ClassLoader in this region cannot be null
MyParcelable2s = 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;
}

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

@ Override
Public void writeToParcel (Parcel dest, int flags ){
// TODO Auto-generated method stub
Dest. writeInt (mInteger );
Dest. writeParcelable (mParcelable, flags );
Dest. writeList (myParcelable2s );
Dest. writeSerializable (mMySerializable );
}

Public static final Parcelable. Creator <MyParcelable> CREATOR = new Creator <MyParcelable> (){

@ Override
Public MyParcelable [] newArray (int size ){
// TODO Auto-generated method stub
Return new MyParcelable [size];
}

@ Override
Public MyParcelable createFromParcel (Parcel source ){
// TODO Auto-generated method stub
Return 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 from the android API documentation. For details, refer to the Android documentation, copy the demo, and replace all the MyParcelable class names, 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.

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.