Learn the Parcelable interface in Android

Source: Internet
Author: User

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.

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?

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.

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.

?
1234 2.实现Parcelable就是为了进行序列化,那么,为什么要序列化?1)永久性保存对象,保存对象的字节序列到本地文件中;2)通过序列化对象在网络中传递对象;3)通过序列化在进程间传递对象。

3.parcelable Interface Definition

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 inheriting class public int            Erface creator<t> {public T createfromparcel (Parcel source);    Public t[] NewArray (int size); }}

4. Implement the Parcelable interface

Let's look at a simple implementation example:

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 define the numeric variable to be passed public String getstr () {return str;    } public void Setstr (String str) {this.str = str;    The public void SetIn (int.) {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 ());         }//Read parcel data, restore the data in the parcel, so that we have a and incoming Myparcelbale object has the same instance variable value of//restored Myparcelable object, so that the object can be passed.        @Override public myparcelable[] NewArray (int size) {return new myparcelable[size]; }    };}

With this foundation, let's take a look at the example of passing values in two activity

The first is the user class, which implements the write and restore of parcel in this user class

User.java

Package Com.example.root.paragainact;import android.os.parcel;import android.os.parcelable;/** * Created by Root on    15-8-15. */public class User implements parcelable {private String username;    private int password;    public int GetPassword () {return password;    } public void SetPassword (int password) {this.password = password;    } public String GetUserName () {return username;    } public void Setusername (String username) {this.username = username;        The public User (String username,int password) {this.password = password;    This.username = Username;    } @Override public int describecontents () {return 0;        } @Override public void Writetoparcel (Parcel dest, int flags) {dest.writestring (GetUserName ());    Dest.writeint (GetPassword ()); public static final creator<user> Creator = new creator<user> () {@Override public User Crea      Tefromparcel (Parcel source) {      return new User (Source.readstring (), Source.readint ());        } @Override Public user[] NewArray (int size) {return new user[size]; }    };}

Mainactivity.java

Package Com.example.root.paragainact;import Android.content.intent;import Android.support.v7.app.actionbaractivity;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import Android.view.view;public class Mainactivity extends Actionbaractivity {@Override prote        CTED void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Findviewbyid (R.id.button). Setonclicklistener (New View.onclicklistener () {@Override public void Oncl                Ick (View v) {Intent i =new Intent (mainactivity.this,anotheract.class);                I.putextra ("User", New User ("admin", 123456));            StartActivity (i);    }        }); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.menu_main, menu);    return true;    }@Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        Noinspection simplifiableifstatement if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}

Anotheract.java

Package Com.example.root.paragainact;import Android.content.intent;import Android.support.v7.app.actionbaractivity;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import Android.widget.textview;public class Anotheract extends Actionbaractivity {private TextV    Iew TV;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_another);        TV = (TextView) Findviewbyid (r.id.tv);        Intent i =getintent ();        User user = I.getparcelableextra ("user");    Tv.settext (String.Format ("User_info (username:%s,password:%d)", User.getusername (), User.getpassword ())); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.menu_another, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        Noinspection simplifiableifstatement if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}

Zhongzhiyuan Nanjing 904727147, Jiangsu

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Learn the Parcelable interface 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.