Parcelable interface usage in Android

Source: Internet
Author: User

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


2. The implementation of Parcelable is for serialization, so why Serialize?


1) Permanently save the object, save the object's byte sequence to the local file;


2) passing objects through a serialized object in the network;


3) Passing objects between processes through serialization.


3. Ways to implement serialization


There are two options for implementing serialization in Android: One is to implement the Serializable interface (which is supported by the javase itself), the first 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.


4. Principles for choosing a serialization method


1) When using memory, parcelable performance is higher than serializable, so we recommend using Parcelable.


2) serializable generates a large number of temporary variables at serialization time, resulting in frequent GC.


3) parcelable can not be used in the case of storing data on disk, because Parcelable does not guarantee the continuity of the data in the event of external change. Although serializable is inefficient, it is recommended to use serializable at this point.


5. Application Scenarios


It is necessary to pass some data between multiple parts (activity or service) through intent, and simple types (such as numbers, strings) can be placed directly into intent. Complex types must implement the Parcelable interface.


6. Parcelable Interface Definition


public interface parcelable {    //content Description interface, basic no 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 parcelable class from the parcel. Because the implementation class is still unknown here, it is necessary to use the template method, inheriting the class name through the template parameters passed into the         //in order to be able to implement the template parameters of the incoming, This defines the creator embedded interface, which contains two interface functions that return individual and multiple instances of inheriting classes         public interface  Creator<T>     {                     public t createfromparcel (Parcel  source);                     public t[] newarray (int size);    }} 

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

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 short: 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.


The code is as follows:


 Public classMyparcelableImplementsParcelable
{     Private intMdata; Public intdescribecontents ()
{         return0; }     Public voidWritetoparcel (Parcel out,intflags)
{Out.writeint (mdata); }     Public Static FinalParcelable.creator<myparcelable>CREATOR=NewParcelable.creator<myparcelable>()
{         Publicmyparcelable Createfromparcel (Parcel in)
{             return Newmyparcelable (in); }         PublicMyparcelable[] NewArray (intsize)
{             return NewMyparcelable[size];         }     }; Privatemyparcelable (Parcel in)
{Mdata=In.readint (); } }

8, serializable implementation and Parcelabel implementation of the difference


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.


Comparison of the two codes:


1) Create the person class to implement serializable


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;     }  &nBsp;     public void setage (int age)     {         this.age = age;    }}

2) Create book class to implement Parcelable


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 ();     }}


Parcelable interface usage 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.