Android serialization object interface Parcelable usage method, androidparcelable

Source: Internet
Author: User

Android serialization object interface Parcelable usage method, androidparcelable

What is Parcelable?

Parcelable defines the interfaces for writing data to Parcel and reading data from Parcel. An object (represented by a class). To encapsulate it in a message, you must implement this interface to implement this interface, this entity becomes "packable.

Parcelable passed object

Android serialization objects can be implemented in two ways:

1. Implement the Serializable interface, which is supported by JavaSE itself;

2. Implement the Parcelable interface. Parcelable is a feature specific to Android and is more efficient than Serializable. It is also supported for Intent data transmission and can also be used for inter-process communication (IPC ),

Except for the basic type, only the classes that implement the Parcelable interface can be put into Parcel.

Parcelable Interface Definition

Public interface Parcelable {// content description interface. You do not need to worry about public int describeContents (); // write the interface function and package public void writeToParcel (Parcel dest, int flags ); // read interface, which is used to construct an instance that implements Parcelable from Parcel. Because the implementation class is unknown here, you need to use the template method. The inherited class name is passed in through the template parameter. // To implement the input of template parameters, the Creator embedded interface is defined here, which contains two interface functions that return one and multiple inherited class instances respectively. 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 to implement the parcelable interface, we need to implement the following methods:

1. describeContents method. Content interface description. By default, 0 is returned;

2. writeToParcel method. This method writes the data of the class to the external provided Parcel. That is, package the data to be transferred to the Parcel container for storage, so that the data can be obtained from the parcel container. This method is declared as follows:

For details about writeToParcel (Parcel dest, int flags), 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 into a Parcelable object and returns the logic layer.

NewArray (int size) creates an array of T type and size. It can only be a single sentence (return new T [size. The method is used for external class deserialization of this class array.

Code Implementation

1. encapsulate data and pass the Person object implementing the parcelable interface to TwoActivity;

Public class DemoActivity extends Activity {/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // encapsulate the data Person p = new Person (); p. setId (1); p. setName ("xiaoming"); // use Intent to pass the Person object Intent I = new Intent (this, TwoActivity. class); I. putExtra ("Person", p); startActivity (I );}}
2. TwoActivity obtains data, parses the Person object passed by DemoActivity, and prints the data;
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());    }}

3. Implementation of the parcelable Interface

Public class Person implements Parcelable {// member variable private int id; private String name; // 1. parcelable must be implemented. creator interface. Otherwise, an error is returned when you obtain the Person data, as shown in the following code: // android. OS. badParcelableException: // Parcelable protocol requires a Parcelable. creator object called CREATOR on class com. um. demo. person // 2. this interface reads the Person data from the Percel container and returns the Person object to the logic layer. // 3. implement Parcelable. the Object Name of the Creator interface must be CREATOR. It is better to report the error mentioned above. // 4. when reading data in the Parcel container, the data must be read in the Order stated by the member variables. Otherwise, an error occurred while obtaining the data. // 5. deserialization object public static final Parcelable. creator <Person> CREATOR = new Creator () {@ Override public Person createFromParcel (Parcel source) {// TODO Auto-generated method stub // The data must be read in the order declared by the member variables. Otherwise, an error occurred while obtaining 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 stub return 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. data must be encapsulated in the order declared by the member variables. Otherwise, an error occurred while obtaining data. // 2. serialized object dest. writeInt (id); dest. writeString (name );}}



How does one save an object on android?

It is recommended to convert to a json string for transmission convenience.
If you want to serialize class objects, the android Team recommends that you use the parcelable interface to explicitly serialize class members, which is much faster than the Serializable interface.

Android issues with Parcelable's createFromParcel and writeToParcel passing Arrays

Have you added Parcelable. Creator to DetailList? Implement createFromParcel (Parcel in)
And the new Array (int size) method?

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.