Usage and difference of parcelable and serializable Interfaces

Source: Internet
Author: User

1. parcelableInterface

Interface for classes whose instances can be written to and restored from a parcel. Classes implementing the parcelable interface must also have a static field called Creator, which is an object implementing the parcelable. Creator interface.

2.ImplementationParcelableIt is for serialization. Why is serialization required?

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.

3.Serialization Method

In Android, there are two options for implementing serialization: one is to implement the serializable interface (which is supported by javase itself), and the other is to implement the parcelable interface (which is a special feature of Android and is more efficient than serializable interface, it can be used for intent data transmission or Interprocess Communication (IPC )). The implementation of the serializable interface is very simple. Just declare it. The implementation of the parcelable interface is a little more complex, but more efficient. We recommend using this method to improve performance.

Note: In Android, intent provides two methods to pass objects: bundle. putserializable (Key, object) and bundle. putparcelable (Key, object ). Of course, these objects have certain conditions. The former implements the serializable interface, while the latter implements the parcelable interface.

4.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.

5.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.

6,ParcelableInterface 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 embedding interface is defined here, contains two interface functions to return the public interface creator <t> {public t createfromparcel (parcel source); Public T [] newarray (INT size );}}

7, ImplementationParcelableProcedure

1) implements parcelable

2) rewrite the writetoparcel method to serialize your object into a parcel object, that is, write the data of the class to the external provided parcel, and package the data to be transferred to the parcel container for storage, to get data from the parcel container

3) override the describecontents method and content interface description. By default, 0 is returned.

4) instantiate static internal Object Creator implementation interface parcelable. Creator

public static final Parcelable.Creator<T> CREATOR

Note:Public static final cannot be less than one, and the name of the internal Object Creator cannot be changed. It must be capitalized. You need to override the two methods in this interface: createfromparcel (parcel in) to read and pass data values from the parcel container, encapsulate them into parcelable objects and return to the logic layer, newarray (INT size) create an array of T type and size. Return New T [size] in only one sentence for external class deserialization.

In short:Use writetoparcel to map your object to a parcel object, and then use createfromparcel to map the parcel object to your object. You can also regard parcel as a stream, write the object to the stream through writetoparcel, and read the object from the stream through createfromparcel, but you need to implement this process, therefore, the write sequence must be consistent with the read sequence.

The Code is as follows:

public class MyParcelable implements Parcelable 
{ private int mData; public int describeContents()
{ return 0; } public void writeToParcel(Parcel out, int flags)
{ out.writeInt(mData); } public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>()
{ public MyParcelable createFromParcel(Parcel in)
{ return new MyParcelable(in); } public MyParcelable[] newArray(int size)
{ return new MyParcelable[size]; } }; private MyParcelable(Parcel in)
{ mData = in.readInt(); } }

8,SerializableImplementation andParcelabelImplementation differences

1) The implementation of serializable only requires implements serializable. This only marks the object and the system will automatically serialize it.

2) The implementation of parcelabel requires not only implements parcelabel, but also adding a static member variable creator to the class. This variable must implement the parcelable. Creator interface.

Code comparison:

1) CreatePersonClass, implementationSerializable

public class Person implements Serializable{    private static final long serialVersionUID = -7060210544600464481L;    private String name;    private int age;        public String getName()    {        return name;    }        public void setName(String name)    {        this.name = name;    }        public int getAge()    {        return age;    }        public void setAge(int age)    {        this.age = age;    }}

2) CreateBookClass, implementationParcelable

public class Book implements Parcelable{    private String bookName;    private String author;    private int publishDate;        public Book()    {            }        public String getBookName()    {        return bookName;    }        public void setBookName(String bookName)    {        this.bookName = bookName;    }        public String getAuthor()    {        return author;    }        public void setAuthor(String author)    {        this.author = author;    }        public int getPublishDate()    {        return publishDate;    }        public void setPublishDate(int publishDate)    {        this.publishDate = publishDate;    }        @Override    public int describeContents()    {        return 0;    }        @Override    public void writeToParcel(Parcel out, int flags)    {        out.writeString(bookName);        out.writeString(author);        out.writeInt(publishDate);    }        public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>()    {        @Override        public Book[] newArray(int size)        {            return new Book[size];        }                @Override        public Book createFromParcel(Parcel in)        {            return new Book(in);        }    };        public Book(Parcel in)    {        bookName = in.readString();        author = in.readString();        publishDate = in.readInt();    }}

Usage and difference of parcelable and serializable Interfaces

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.