Parcelable and Serializable differences

Source: Internet
Author: User
Tags object serialization

When data is passed between activity, in order to avoid trouble, some values are often encapsulated as objects, and then the entire object is passed through. When transmitting an object, there are two cases, one is to implement Parcelable interface and one is to implement serializable interface.

One, explain the two kinds of interfaces:

1) The implementation of the serializable interface is supported by Javase itself.

2) Parcelable is an Android-specific feature that is more efficient than the serializable interface, which is supported for intent data transfer, and can also be used in interprocess communication (IPC), in addition to the basic types, Only classes that implement the Parcelable interface can be placed in the parcel.

3) When do I use serialization?

A) When you want to write an object in memory to the hard disk;
b) When you want to use sockets to transfer objects on the network;
c) When you want to transfer objects through RMI;

To explain a little bit more: a) For example, your memory is not enough, the computer will be a part of the memory of the object temporarily saved to the hard disk, and then to use the time to read into the memory, the hard disk that part of the storage space is called virtual memory. In the case of you want to save a particular object to a file, I take it out every few days, then the implementation of the Serializable interface;
b) In the Java socket programming, you may sometimes want to transfer a certain class of objects, then also implement the serializable interface; the most common you transmit a string, it is the class inside the JDK, also implements the Serializable interface, So it can be transmitted over the network.
c) If you want to invoke a method of a remote object through a remote method call (RMI), such as a method of invoking another Computer B object in Computer A, you need to implement the serialization interface by obtaining a reference to the computer B target object through the Jndi service and transferring the object from B to a.

second, what is the Parcelable interface?

1) parcelable, defines the interface that writes data to parcel, and reads from parcel. An entity (represented by a class), if it needs to be encapsulated in a message, the interface must be implemented and the interface is implemented, and the entity becomes "packaged".

2) Definition of parcelable interface:

 Public Interfaceparcelable {//content Description interface, basic no tube             Public intdescribecontents (); //Write interface functions, packaging             Public voidWritetoparcel (Parcel dest,intflags); //read interface, the purpose is to construct an instance processing of the class that implements the parcelable from the parcel.            Because the implementation class is still unknown here, it is necessary to use the template's way of inheriting the class name passed through the template parameter. //To enable the introduction of template parameters, the creator embedded interface is defined here, with two interface functions returning individual and multiple instances of inheriting classes.              Public InterfaceCreator<t> {                 PublicT Createfromparcel (Parcel source);  PublicT[] NewArray (intsize); }        }

3) How to implement Parcelable interface?

From the Parcelable interface definition, we can see that implementing the Parcelable interface requires us to implement the following methods:

(1.) Describecontents method. Content interface Description, default return 0 can be;

(2.) Writetoparcel method. This method writes the data for the class to an externally supplied parcel. That is, packaging the data to be passed to the parcel container to save the data from the parcel container, which is declared as follows:

Writetoparcel (Parcel dest, int flags) See DOC documentation for specific parameter meanings

(3) A static Parcelable.creator interface, this interface has two methods:

Createfromparcel (Parcel in) reads the passed data value from the Parcel container and encapsulates it as a Parcelable object to return to the logical layer.

NewArray (int size) creates an array of type T, length size, and only one sentence (return new t[size]). method is used by the outer class to deserialize the array of this class.

4) Code Implementation >

(1.) Implement the Myparcelable class:

 Packagecom.jyxp.my.parcelable;Importjava.util.ArrayList;Importjava.util.List;ImportAndroid.os.Parcel;Importandroid.os.Parcelable; Public classMyparcelableImplementsparcelable {Private intMinteger; PrivateMyParcelable2 mparcelable; PrivateList<myparcelable2> Myparcelable2s =NewArraylist<myparcelable2>(); Privatemyserializable mmyserializable;  Publicmyparcelable () {//TODO auto-generated Constructor stub} @SuppressWarnings ("Unchecked")     Publicmyparcelable (Parcel in) {//TODO auto-generated Constructor stubMinteger =In.readint (); Mparcelable= In.readparcelable (MyParcelable2.class. getClassLoader ());//The ClassLoader of this place cannot be null.Myparcelable2s = In.readarraylist (MyParcelable2.class. getClassLoader ()); Mmyserializable=(myserializable) in.readserializable (); }     Public intGetminteger () {returnMinteger; }     Public voidSetminteger (intMinteger) {         This. Minteger =Minteger; }     PublicMyParcelable2 getmparcelable () {returnmparcelable; }     Public voidsetmparcelable (MyParcelable2 mparcelable) { This. mparcelable =mparcelable; }     PublicList<myparcelable2>Getmyparcelable2s () {returnMyparcelable2s; }     Public voidSetmyparcelable2s (list<myparcelable2>myparcelable2s) {         This. Myparcelable2s =Myparcelable2s; }     Publicmyserializable getmmyserializable () {returnmmyserializable; }     Public voidsetmmyserializable (myserializable mmyserializable) { This. mmyserializable =mmyserializable; } @Override Public intdescribecontents () {//TODO auto-generated Method Stub        return0; } @Override Public voidWritetoparcel (Parcel dest,intflags) {        //TODO auto-generated Method StubDest.writeint (Minteger);        Dest.writeparcelable (mparcelable, flags);        Dest.writelist (MYPARCELABLE2S);            Dest.writeserializable (mmyserializable); }         Public Static FinalParcelable.creator<myparcelable> Creator =NewCreator<myparcelable>() {@Override PublicMyparcelable[] NewArray (intsize) {            //TODO auto-generated Method Stub            return NewMyparcelable[size]; } @Override Publicmyparcelable Createfromparcel (Parcel source) {//TODO auto-generated Method Stub            return Newmyparcelable (source); }    };}

Attention:

1, must implement Parcelable.creator interface, and access control must be public!!; Implement Parcelable.creator interface object name must be creator!! Otherwise, when the data is obtained, the error will be as follows: Android.os.BadParcelableException:

2. When reading the data in the parcel container, the data must be read in the order declared by the member variable, otherwise there will be error in getting the data.

3, note parcel out and in the corresponding attribute order can not be wrong, otherwise not get value; If you want to pass a value that does not have write and read, you also get a value that is not.

4, the implementation of Parcelable interface I use the approach is to find the Parcelable interface from the Android API documentation, see the Android document , the demo copy, and then replace the Myparcelable class name, Fill in the write and read values again. The above code gives some examples when filling in the values, and sometimes the following errors occur:

(1,) caused By:android.os.BadParcelableException:ClassNotFoundException when unmarshalling, because ClassLoader is not set, or no incoming classloader.

(2) Java.lang.RuntimeException:Parcelable encountered IOException writing serializable object, The reason is that the objects inside the Parcelable object are passed parcelable or serializable.

third, what is the serializable interface?

1) An object serialization interface, a class only implements the Serializable interface, its object is serializable. Therefore, if you want to serialize objects of some classes, these classes must implement the Serializable interface. In fact, serializable is an empty interface, nothing specific, its purpose is simply to identify a class of objects can be serialized.

2) How to implement Serializable interface?

Very simple, as long as the implements serializable interface can be

3) Code Implementation >

 Packagecom.jyxp.my.parcelable;Importjava.io.Serializable; Public classMyserializableImplementsSerializable {Private Static Final LongSerialversionuid = 1L; PrivateDouble mdouble; PrivateFloat mfloat;  Publicmyserializable () {//TODO auto-generated Constructor stub    }     PublicDouble getmdouble () {returnmdouble; }     Public voidsetmdouble (Double mdouble) { This. mdouble =mdouble; }     PublicFloat getmfloat () {returnmfloat; }     Public voidsetmfloat (Float mfloat) { This. Mfloat =mfloat; }}

Iv. How to achieve the value of the transmission

1) Basic data type, you can

2) When passing a serializable object, the custom member object inside the passed serializable object (not the serializable object in the API) also implements the serializable interface, or caused by: Java.io.NotSerializableException exception. As can be seen from the above code, in the Parcelable object can be passed serializable object, but serializable object within the time to pass the parcelable? The answer is no, and the same will produce java.io.NotSerializableException anomalies.

3) The Android API can only pass a collection of Parcelable objects, not a collection of serializable objects, which can only be passed ARRAYLIST<BITMAP>, but cannot be passed arraylist< Designer>. Just started to learn Android, objects are encapsulated into serializable, and then pass, because Serializable is javase inside of the localization interface, very familiar with, at that time also raised doubts, why there will be parcelable interface, what is the difference between the two? Later, when the serializable can not meet the requirements of the time to understand that Android use pacelable to encapsulate their own things, like workers in the bitmap, in the read can not need to set ClassLoader.

4) It is also possible to pass enum Enum as a class.

5) Short, char, charsequence, MAP, list are not supported, it is recommended to change to int, string, string, HashMap, ArrayList.

6) Android Studio recommends installing Android Parcelable code generation Plugin, direct alt+insert to find parcelable on it.

Parcelable and Serializable differences

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.