Learn the Parcelable interface in Android

Source: Internet
Author: User
<span id="Label3"></p><p><p>Soon after the contact with the table, I will be studying the development of the table for a long time afterwards. Just to realize your own ideas.</p></p> <p><p>1. First of all to say parcelable before you have to say, serializable interface. Read a lot of tutorials, said activity value transfer process is to first say serializable interface, then the parvelable interface. Two interfaces similar, what is the difference?</p></p> <pre class="best-text mb-10"><pre class="best-text mb-10">The function, efficiency, difference and choice of parcelable and serializable: 1, function serializable function is to save the Object's property to local file, database, network stream, RMI to facilitate data transmission, of course, this transmission can be within the program or between two Programs. The Android Parcelable is designed to be slow to serializable, designed to transfer data between different components within the program and between different Android programs, which are only available in memory, Parcelable is the carrier of the message through IBinder Communication. From the above design we can see the pros and cons. 2, efficiency and Choice parcelable performance than serializable good, in memory overhead, so it is recommended to use parcelable in memory data transfer, such as transfer of data between activity, and serializable can persist data for easy preservation , so choose serializable when you need to save or network transfer data, because Android different version parcelable may be different, so it is not recommended to use parcelable for data persistence 3, programming implementation for serializable, Class only needs to implement the serializable interface and provide a serialized version ID (serialversionuid). parcelable, however, needs to implement writetoparcel, describecontents functions, and static variables, essentially defining how to package and reconcile the work itself, and the serialization of these operations is done entirely by the Underlying.</pre></pre> <p><p>Parcelable Interface: An instance that implements the Parcelable interface can write its own state information (state information usually refers to the value of each member Variable) to parcel, or restore its state from parcel. Parcel is used to complete the serialization of data transfer.</p></p> <pre class="brush:java;toolbar: true; auto-links: false;"><pre class="brush:java;toolbar: true; auto-links: false;">2. The implementation of parcelable is for serialization, so why serialize? 1) persist the object, save the Object's byte sequence to the local file, 2) pass the object over the network through the serialized object, and 3) pass the object between processes through Serialization.</pre></pre> <p><p>3.<span style="font-size: 15px;">parcelable Interface Definition</span></p></p> <p><p><span style="font-size: 15px;"></span></p></p> <pre><pre> 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 a class that implements the parcelable 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          //in order to be able to implement the template parameters of the incoming, defined here creator Embedded interface, contains two interface functions to return a single and multiple instances of inheritance class           public interface Creator<T>     {                public t createfromparcel (Parcel  source);             public t[] newarray ( int size);     }} </pre></pre> <p><p><span style="font-size: 15px;">4. Implement the <span style="font-size: 15px;">Parcelable interface</span><br></span></p></p> <p><p><span style="font-size: 15px;">Let's look at a simple implementation example:</span></p></p> <pre class="brush:java;toolbar: true; auto-links: false;">package com.example.root.pracact;import android.os.parcel;import android.os.parcelable;/**  * Created by root on 15-8-14. */public class MyParcelable  implements parcelable {    private string str;     Private int in;    public myparcelable (string str, int in)  {        this.str=  str;         this.in = in;    }    //first defines the numeric variables to be passed      public string getstr ()  {         Return str;    }    public void setstr (String str)  {        this.str = str;    }     publIc void setin (int in)  {        this.in =  in;    }    public int getin ()  {         return in;    }     @Override     public int describecontents ()  {         return 0;    }     @Override      Public void writetoparcel (parcel dest, int flags)  {         dest.writestring (str);         dest.writeint (in );     }    //write Operation writes data to parcel     public  Static final creator<myparcelable> creator = new creator<myparcelable > ()  {         @Override         public myparcelable  createfromparcel (parcel source)  {             return new myparcelable (source.readstring (), source.readint ());         }        //reads The parcel data, restores the data in the parcel, So we have a Myparcelbale object with the same instance variable value as the passed in         //  The restored myparcelable object, which enables the object to be Passed.          @Override          Public myparcelable[] newarray (int size)  {             return new MyParcelable[size];         }    };}</pre> <p><p>With this foundation, let's take a look at the example of passing values in two activity</p></p> <p><p>The first is the user class, which implements the write and restore of parcel in this user class<br></p></p> <pre>com.example.root.pracact;android.os.parcel;android.os.parcelable; user parcelable{    string ;    ;     Setage (age)  {        .= age;    }     getage ()  {        ;    }     setname (string name)  {        .=  name;    }    string getname ()  {         ;    }    user (String name,age) {         .= name;        . = age;    }    describecontents ()  {         ;    }    Writetoparcel (parcel dest, flags)  {         Dest.writestring (getName ());         dest.writeint (getAge ());     }    Creator<User> = Creator<User> ()  {         user createfromparcel (parcel source)  {             user (source.readstring (), source.readInt ());         }        User[]  NewArray (size)  {            User[size];         }    };}</pre> <pre>com.example.root.pracact;android.content.intent;android.support.v7.app.actionbaractivity;android.os.bundle; android.view.menu;android.view.menuitem;android.view.view;java.io.serializable; Mainactivity actionbaractivity {    oncreate (bundle savedinstancestate)  {        .oncreate (savedinstancestate);         setcontentview (r.layout.);         findviewbyid (r.id.). Setonclicklistener (view.onclicklistener ()  {             onclick (view v)  {                 intent i = intent (mainactivity.,anotheract.); I.putextra (,  user (,)); startactivity (i);             }        });  &nbsP;  }    oncreateoptionsmenu (menu menu)  {         getmenuinflater (). Inflate (r.menu., menu);         ;    }    onoptionsitemselected (MenuItem item)  {         id = item.getitemid ();          (id == r.id.)  {            ;         }        .onoptionsitemselected (item);     }}</pre> <pre>com.example.root.pracact;android.content.intent;android.support.v7.app.actionbaractivity;android.os.bundle; android.view.menu;android.view.menuitem;android.widget.textview; anotheract actionbaractivity {    textview ;     OnCreate (bundle savedinstancestate)  {        .oncreate ( savedinstancestate);         setcontentview (R.layout.);         =  (TextView)  findviewbyid (r.id.);         intent i =getintent ();         user user =  i.getparcelableextra ();         .settext (String. (, user.getname (), user.getage ()));    }     Oncreateoptionsmenu (menu menu)  {        getmenuinflater (). Inflate (r.menu., menu);        ;    }     onoptionsitemselected (menuitem item)  {         id = item.getitemid ();         (id == R.id.)  {            ;         }        .onoptionsitemselected (item);     }}</pre> <p><p>Zhongzhiyuan Nanjing 904727147, Jiangsu<br></p></p><p><p>Learn the Parcelable interface in Android</p></p></span>
Related Article

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.