Parcelable interface and serializable usage and differences in Android

Source: Internet
Author: User

Parcelable Interface:

Interface for classes whose instances can is written to and restored from a Parcel. Classes implementing the Parcelable interface must also has a static field called CREATOR, which is an object Implementin G The Parcelable.creator interface

An instance of a class can be written to and stored in a package interface. the class that implements the Parcelable interface must also have a static variable CREATOR, which is an object that implements the Parcelable.creator interface

Reasons and benefits of serialization:

1, passing objects through a serialized object in the network;
2, passing objects between processes through serialization.

Two ways to implement serialization:

One is to implement the Serializable interface (which is supported by the javase itself), one is to implement the Parcelable interface (Android-specific features, efficiency than the implementation of serializable interface efficient , can be used for intent data transfer, or for interprocess communication (IPC). The implementation of the serializable interface is very simple, declare it, and the implementation of the Parcelable interface is slightly more complex, but more efficient, it is recommended that this method to improve performance .

Note: There are two ways to pass objects intent in Android: one is bundle.putserializable (Key,object) and the other is Bundle.putparcelable (Key,object). Of course, these objects have certain conditions, the former is the implementation of the serializable interface, and the latter is the implementation of the Parcelable interface.

Definition of the Parcelable interface:

Public interface Parcelable {    //Content Description interface, basic without tube public    int describecontents ();    Write interface function, package public    void Writetoparcel (Parcel dest, int flags);    Read interface, the purpose is to construct an instance processing of the class that implements the parcelable from the parcel. Because the implementation of the class is still unknown here, it is necessary to use the template way, inheriting the class name through the template parameters passed in    //in order to be able to implement the template parameters of the incoming, here is defined creator embedded interface, contains two interface functions to return single and multiple instances of inheritance class public    Interface creator<t>     {public           T createfromparcel (Parcel source);           Public t[] NewArray (int size);}    }

To implement parcelable steps:

1) Implements Parcelable
2) Rewrite the Writetoparcel method to serialize your object to a parcel object, that is, to write the data of the class to an externally supplied parcel, to package the data that needs to be passed to the parcel container to save the data from the parcel container
3) Rewrite the Describecontents method, the Content interface description, the default return 0 can be
4) instantiate the static internal object Creator Implement Interface Parcelable.creator

public static final Parcelable.creator<t> Creator
To implement an object that Parcelable internal interface creator, you must implement two methods:

Note: the public static final one can not be less, the internal object creator name can not be changed , must all uppercase. The two methods in this interface need to be rewritten: the Createfromparcel (Parcel in) Implementation reads the passed data value from the Parcel container, encapsulates the Parcelable object to return the logical layer, and newarray (int size) creates a type of T, An array of size length, with just one sentence (return new t[size]), for the outer class to deserialize the array of this class.

In summary: Map your objects into parcel objects through writetoparcel, and then map parcel objects to your objects through Createfromparcel. It is also possible to think of parcel as a stream through which the object is written to the stream through the Writetoparcel, and the object is read from the stream through the Createfromparcel, but this process needs to be done, so the order of writing and the order of reading must be consistent.

Code:

1, implement Parcelable interface

Package Com.hust.bean;import Android.graphics.bitmap;import Android.os.parcel;import android.os.parcelable;public Class Book implements Parcelable {//Implement Parcelable interface/* * Book Properties * */private String title= "";//title Private Bitmap cover;//cover p Rivate string Author= "";//Author private string publisher= "";//Publisher private string Publishdate= "";//Publication date private string isbn= " ";//isbnprivate String summary=" ";//Introduction @overridepublic int describecontents () {//TODO auto-generated method Stubreturn 0 ;} Write to Parcel @overridepublic void Writetoparcel (Parcel dest, int flags) {//TODO auto-generated method Stubdest.writestring (Title);d est.writeparcelable (Cover, Flags);d est.writestring (Author);d est.writestring (            Publisher);d est.writestring (publishdate);d est.writestring (ISBN);d est.writestring (Summary); }//must instantiate Parcelable's internal interface Creator, a word cannot be public static final parcelable.creator<book> creator=new creator< Book> () {//read from Pacel container @overridepublic book createfromparcel (Parcel source) {//TODO Auto-generated Method Stubbook book=new book (); Title=source.readstring (); Cover=source.readparcelable (Bitmap.class.getClassLoader ()); Author=source.readstring (); Publisher=source.readstring (); Publishdate=source.readstring (); Isbn=source.readstring (); Summary=source.readstring (); return book;} @Overridepublic book[] NewArray (int size) {//TODO auto-generated method Stubreturn new Book[size];}}; Public String GetTitle () {return Title;} public void Settitle (String title) {title = title;} Public Bitmap Getcover () {return Cover;} public void Setcover (Bitmap cover) {cover = cover;} Public String Getauthor () {return Author;} public void Setauthor (String author) {author = author;} Public String Getpublisher () {return Publisher;} public void Setpublisher (String publisher) {publisher = publisher;} Public String Getpublishdate () {return publishdate;} public void Setpublishdate (String publishdate) {publishdate = publishdate;} Public String GETISBN () {return ISBN;} public void Setisbn (STring ISBN) {isbn = ISBN;} Public String getsummary () {return Summary;} public void Setsummary (String summary) {summary = Summary;}}


2, realizeSerializable Interface

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.)    {        this.age = age;    }}


The difference between serializable implementation and Parcelabel implementation
1) Serializable implementation, only need implements Serializable can. This simply marks the object and the system automatically serializes it.
2) Parcelabel implementation, not only need to implements Parcelabel, but also to add a static member variable Creator in the class, this variable needs to implement the Parcelable.creator interface .
Reference: Http://www.cnblogs.com/renqingping/archive/2012/10/25/Parcelable.html




Parcelable interface and serializable usage and differences in Android

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.