Android serialized Object Interface Parcelable use method

Source: Internet
Author: User

What is parcelable?

Parcelable, defines the interface that writes data to parcel, and reads from parcel. An entity (represented by a class), if it needs to be encapsulated in a message, the interface must be implemented and the interface is implemented, and the entity becomes "packaged".

Parcelable Passing objects

There are two main ways to serialize an Android object:

1. Implement serializable interface, implement serializable interface is javase itself support;

2. Implement the Parcelable interface, Parcelable is a unique feature of Android, the efficiency is higher than the implementation of serializable interface, like for intent data transmission also support, but also can be used in interprocess communication (IPC),

In addition to the basic types, only classes that implement the Parcelable interface can be placed in parcel.

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 class is still unknown here, it is necessary to use the template's way of inheriting the class name passed through the template parameter.    //In order to enable the introduction of template parameters, this defines the creator embedded interface, which contains two interface functions to return individual and multiple instances of inheriting classes. Public    interface Creator<t> {public           T createfromparcel (Parcel source);           Public t[] NewArray (int size);       }

Implement the Parcelable interface?

from the Parcelable interface definition, we can see that implementing the Parcelable interface requires us to implement the following methods:

1.describeContents method. Content interface Description, default return 0 can be;

2.writeToParcel method. This method writes the data for the class to an externally supplied parcel. That is, packaging the data to be passed to the parcel container to save the data from the parcel container, which is declared as follows:

Writetoparcel (Parcel dest, int flags) The meaning of the specific parameters see Javadoc

3. Static Parcelable.creator interface, this interface has two methods:

Createfromparcel (Parcel in) reads the passed data value from the Parcel container and encapsulates it as a Parcelable object to return to the logical layer.

NewArray (int size) creates an array of type T, length size, and only one sentence (return new t[size]). method is used by the outer class to deserialize the array of this class.

Code implementation

1. Encapsulate the data and pass the person object that implements the Parcelable interface to the twoactivity;

public class Demoactivity extends activity {    /** called when the activity is first created. */    @Override    publi c void OnCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.main);        Encapsulate data person        p = new Person ();        P.setid (1);        P.setname ("Xiaoming");        Pass the person object with Intent        Intent i = new Intent (this, twoactivity.class);        I.putextra ("Person", p);        StartActivity (i);    }}
2.TwoActivity Gets the data, from the demoactivity passed the person object to parse and print;
public class Twoactivity extends Activity {    @Override    protected void onCreate (Bundle savedinstancestate) {        TODO auto-generated Method Stub        super.oncreate (Savedinstancestate);                Person P = (person) getintent (). Getparcelableextra ("person");                System.out.println ("p_id" +p.getid ());        System.out.println ("P_name" +p.getname ());}    }

implementation of the 3.parcelable interface

public class Person implements parcelable{//member variable private int ID;        private String name; 1. The Parcelable.creator interface must be implemented, otherwise, when the person data is obtained, the error is as follows://android.os.BadParcelableException://parcelable protocol Requires a Parcelable.creator object called Creator on class Com.um.demo.Person//2. This interface implements the reading of the person data from the Percel container and returns the per The son object is used for the logical layer//3. The implementation of the Parcelable.creator interface object name must be creator, as well as the error mentioned above;//4. In reading the data in the parcel container, the data must be read in the order declared by the member variable. Otherwise there will be error getting data//5. Deserialization object public static final parcelable.creator<person> Creator = new Creator () {@Overri De public person Createfromparcel (Parcel source) {//TODO auto-generated Method Stub//must be pressed into            The data is read in the order of the member variable declaration, or there will be an error getting the data person P = new person ();            P.setid (Source.readint ());            P.setname (Source.readstring ());        return p;            } @Override Public person[] NewArray (int size) {//TODO auto-generated method stubreturn new Person[size];        }    };    public int getId () {return id;    } public void setId (int id) {this.id = ID;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } @Override public int describecontents () {//TODO auto-generated method stub return 0; } @Override public void Writetoparcel (Parcel dest, int flags) {//TODO auto-generated method Stub//        1. The data must be encapsulated in the order in which the member variable is declared, otherwise there will be error getting data//2. Serialized object Dest.writeint (ID);    Dest.writestring (name); }}


Android serialized Object Interface Parcelable use method

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.