Understanding and difference between Serializable and Parcelable serialization,
I. Why serialization for android? What is serialization and how to serialize
Why
Why is serialization required? -- During Android development, objects cannot be referenced to Activities or Fragments. We need to put these objects in an Intent or Bundle before passing them.
What
What is serialization-serialization, which indicates converting an object to a storage or transmission state. Serialized objects can be transmitted over the network or stored locally.
How
How to transmit objects through serialization?
In Android, Intent can be implemented in two ways to pass class objects.
Method 1: Serializable. The class to be passed implements the Serializable interface to pass objects,
Method 2: Parcelable. The class to be passed implements the Parcelable interface to pass objects.
Serializable (Java built-in ):
Serializable refers to serialization, which refers to converting an object into a storage or transmission state. Serialized objects can be transmitted over the network or stored locally.
Parcelable (for android ):
In addition to Serializable, Parcelable can also achieve the same effect,
However, unlike Object serialization, Parcelable achieves the principle of decomposing a complete object,
Each part after decomposition is the data type supported by Intent, so that the object can be transferred.
Functions of implementing Parcelable
1) permanently Save the object and save the object's byte sequence to a local file;
2) passing objects in the network by serializing objects;
3) objects are transmitted between processes through serialization.
Principles for selecting serialization Methods
1) when using memory, Parcelable has higher performance than Serializable, so Parcelable is recommended.
2) Serializable will generate a large number of temporary variables during serialization, resulting in frequent GC.
3) Parcelable cannot be used when you want to store data on a disk, because Parcelable cannot guarantee data continuity in the case of external changes. Although the Serializable efficiency is low, we recommend using Serializable.
Application scenarios
Some data needs to be transmitted between multiple components (Activity or Service) through Intent. Simple types (such as numbers and strings) can be directly placed into Intent. Complex types must implement the Parcelable interface.
Ii. Example of serialization using java's built-in Serializable
Get an object class Person and use the Serializable of Java for serialization.
Package com. amqr. serializabletest. entity;
Import java. io. Serializable;
/** * User: LJM * Date&Time: 2016-02-22 & 14:16 * Describe: Describe Text */public class Person implements Serializable{ private static final long serialVersionUID = 7382351359868556980L; private String name; private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
Use MainActivity and SecondActivity
MainActivity
Package com. amqr. serializabletest; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import android. widget. textView; import com. amqr. serializabletest. entity. person;/*** during Android development, we all know that objects cannot be referenced to Activities or Fragments. * we need to put these objects in an Intent or Bundle, and then pass. * ** In Android, Intent can be implemented in two ways to pass class objects. * Method 1: Serializable. The class to be passed implements the Serializable interface to pass objects. * Method 2: Parcelable. The class to be passed implements the Parcelable interface to pass objects. ** Serializable (Java built-in): * Serializable refers to serialization, which refers to converting an object into a storage or transmitting State. Serialized objects can be transmitted over the network or stored locally. ** Parcelable (android-specific): * In addition to Serializable, Parcelable can also achieve the same effect. * unlike Object serialization, the implementation principle of Parcelable mode is to break down a complete object. * each part after decomposition is the data type supported by Intent, so that the object can be passed. The objects to be passed must implement one of the above two interfaces before they can be passed directly through Intent. */Public class MainActivity extends Activity {private TextView mTvOpenNew; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); findViewById (R. id. mTvOpenNew ). setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Intent open = new Intent (MainActivity. this, SecondActivity. class); Person person = new Person (); person. setName ("1 to 2 to 3"); person. setAge (18); // transmission method 1. intent directly calls putExtra // public Intent putExtra (String name, Serializable value) open. putExtra ("put_ser_test", person); // transfer method 2. intent uses putExtras (Note s) to pass in bundle/** Bundle bundle = new Bundle (); bundle. putSerializable ("bundle_ser", person); open. putExtras (bundle); */startActivity (open );}});}}
SecondActiviy
Package com. amqr. serializabletest; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. widget. textView; import com. amqr. serializabletest. entity. person;/*** User: LJM * Date & Time: 2016-02-22 & 11:56 * Describe: Describe Text */public class SecondActivity extends Activity {private TextView mTvDate; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_second); mTvDate = (TextView) findViewById (R. id. mTvDate); Intent intent = getIntent (); // key method: getSerializableExtra. Our class implements the Serializable interface, so write this method to get the object // public class Person implements Serializable Person per = (Person) intent. getSerializableExtra ("put_ser_test"); // Person per = (Person) intent. getSerializableExtra ("bundle_ser"); mTvDate. setText ("name:" + per. getName () + "\ n" + "Age:" + per. getAge ());}}
This completes Serializable.
Iii. android-specific Parcelable serialization example
We write an object class to implement the Parcelable interface, which is immediately required.
1. describeContents method and writeToParcel Method
2. instantiate the static internal Object CREATOR and implement the interface Parcelable. Creator.
That is, the Parcelable interface implemented by any class will become like this at the beginning.
The implementation principle of Parcelable mode is to break down a complete object, and each part after the decomposition is the data type supported by Intent, so that the object transfer function is realized.
public class Pen implements Parcelable{ private String color; private int size; protected Pen(Parcel in) { color = in.readString(); size = in.readInt(); } public static final Creator
CREATOR = new Creator
() { @Override public Pen createFromParcel(Parcel in) { return new Pen(in); } @Override public Pen[] newArray(int size) { return new Pen[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(color); dest.writeInt(size); }}
The system has already done a lot of things for us. What we need to do is simply write the constructor we need and write the get and set of private variables.
This is probably the case:
Package com. amqr. serializabletest. entity; import android. OS. parcel; import android. OS. parcelable;/*** User: LJM * Date & Time: 2016-02-22 & 14:52 * Describe: Describe Text */public class Pen implements Parcelable {private String color; private int size; // automatically add it to createFromParcel with protected Pen (Parcel in) {color = in. readString (); size = in. readInt ();} public static final Creator
CREATOR = new Creator
() {/***** @ Param in * @ return * in the createFromParcel () method, we need to read the name and age fields just written, * and create a Person object to return, color and size are read by calling the readXxx () method of Parcel. * Note that the read order must be exactly the same as that just written. * Reading is completed using a constructor */@ Override public Pen createFromParcel (Parcel in) {return new Pen (in ); // read completed in the constructor} // @ Override public Pen [] newArray (int size) called for deserialization of this class Array) {return new Pen [size] ;}};@ Override public int describeContents () {return 0; // content interface description. By default, 0 is returned.} @ Override public void writeToParcel (Parcel dest, int flags) {dest. writeString (color); // write the color dest. writeInt (size); // write size} // ====== split line, write get and set // Add public Pen () by yourself () {}// add public Pen (String color, int size) {this. color = color; this. size = size;} public String getColor () {return color;} public void setColor (String color) {this. color = color;} public int getSize () {return size;} public void setSize (int size) {this. size = size ;}}
In fact, writing Parcelable is not very troublesome. In as, after writing private variables in an object class, let this class inherit from Parcelable. The next step is:
1. Two Methods of rewriting: describeContents and writeToParcel
2. instantiate the static internal Object CREATOR and implement the interface Parcelable. Creator. The above two-step system has already helped us automate the process.
3. Write the required constructor, get and set of variables.
The implementation of the Self-Parcelable object Bean has been written. Next we will use the following in combination with MainActivity and ThirdActivity:
MainActivity
Package com. amqr. serializabletest; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import com. amqr. serializabletest. entity. pen; import com. amqr. serializabletest. entity. person;/*** during Android development, we all know that objects cannot be referenced to Activities or Fragments. * we need to put these objects in an Intent or Bundle, and then pass. * ** In Android, Intent can be implemented in two ways to pass class objects. * Method 1: Serializable. The class to be passed implements the Serializable interface to pass objects. * Method 2: Parcelable. The class to be passed implements the Parcelable interface to pass objects. ** Serializable (Java built-in): * Serializable refers to serialization, which refers to converting an object into a storage or transmitting State. Serialized objects can be transmitted over the network or stored locally. ** Parcelable (android-specific): * In addition to Serializable, Parcelable can also achieve the same effect. * unlike Object serialization, the implementation principle of Parcelable mode is to break down a complete object. * each part after decomposition is the data type supported by Intent, so that the object can be passed. The objects to be passed must implement one of the above two interfaces before they can be passed directly through Intent. */Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); findViewById (R. id. mTvOpenNew ). setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Intent open = new Intent (MainActivity. this, SecondActivity. class); Person person = new Person (); person. setName ("1 to 2 to 3"); person. setAge (18); // transmission method 1. intent directly calls putExtra // public Intent putExtra (String name, Serializable value) open. putExtra ("put_ser_test", person); // transfer method 2. intent uses putExtras (Note s) to pass in bundle/** Bundle bundle = new Bundle (); bundle. putSerializable ("bundle_ser", person); open. putExtras (bundle); */startActivity (open) ;}}); // use Parcelable findViewById (R. id. mTvOpenThird ). setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Intent mTvOpenThird = new Intent (MainActivity. this, ThirdActivity. class); Pen tranPen = new Pen (); tranPen. setColor ("big red"); tranPen. setSize (98); // public Intent putExtra (String name, Parcelable value) mTvOpenThird. putExtra ("parcel_test", tranPen); startActivity (mTvOpenThird );}});}}
ThirdActivity
Package com. amqr. serializabletest; import android. app. activity; import android. OS. bundle; import android. widget. textView; import com. amqr. serializabletest. entity. pen;/*** User: LJM * Date & Time: 2016-02-22 & 14:47 * Describe: Describe Text */public class ThirdActivity extends Activity {private TextView mTvThirdDate; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_third); mTvThirdDate = (TextView) findViewById (R. id. mTvThirdDate); // Intent intent = getIntent (); // Pen pen = (Pen) intent. getParcelableExtra ("parcel_test"); Pen pen = (Pen) getIntent (). getParcelableExtra ("parcel_test"); mTvThirdDate = (TextView) findViewById (R. id. mTvThirdDate); mTvThirdDate. setText ("color:" + pen. getColor () + "\ n" + "Size:" + pen. getSize ());}}
Complete: Serializable and Parcelable are both described. Next let's talk about comparison
Iv. Comparison of Serializable and Parcelable
Use Parcelable on android as much as possible, so efficiency is the highest.
Encoding:
Less Serializable code, easy to write
More Parcelable code
Efficiency:
Parcelable is faster than 10 times faster
The charm of serializable is that you only need to implement the Serializable interface for a class and its attributes. The Serializable interface is a marker interface, which means that Java will perform efficient serialization operations on this object without implementation methods.
The disadvantage of this method is that reflection is used, and the serialization process is slow. This mechanism will create many temporary objects during serialization and easily trigger garbage collection.
The implementation principle of Parcelable mode is to break down a complete object, and each part after the decomposition is the data type supported by Intent, so that the object passing function is realized.