Parcelable interface usage in Android

1. Parcelable interface

 

Interface for classes whose instances can be written to and restored from a Parcel。 Classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creator interface。

 

2. Implementing Parcelable is for serialization, so why serialize?

 

1) Permanently save the object, save the byte sequence of the object to a local file;

 

2) Pass objects across the network by serializing them;

 

3) Pass objects between processes through serialization.

 

3. The method of implementing serialization

 

There are two options for implementing serialization in Android: one is to implement the Serializable interface (which is supported by JavaSE itself), the other is to implement the Parcelable interface (an Android-specific function, the efficiency is more efficient than the implementation of the Serializable interface, it can be used for Intent data transfer, or for inter-process communication (IPC)). Implementing the Serializable interface is very simple, just declare it, while implementing the Parcelable interface is a little more complicated, but more efficient, it is recommended to use this method to improve performance.

 

Note: There are two methods for passing objects in 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 implements the Serializable interface, while the latter implements the Parcelable interface.

 

4. Principles for choosing serialization methods

 

1) When using memory, Parcelable has higher performance than Serializable, so Parcelable is recommended.

 

2) Serializable will generate a large number of temporary variables during serialization, which will cause frequent GC.

 

3) Parcelable cannot be used in the case where data is to be stored on disk, because Parcelable cannot guarantee the persistence of data in the case of changes in the outside world. Although Serializable is inefficient, it is recommended to use Serializable at this time.

 

5. Application scenarios

 

Need to pass some data between multiple components (Activity or Service) through Intent, simple types (such as: numbers, strings) can be directly put into Intent. Complex types must implement the Parcelable interface.

 

6. Parcelable interface definition

 

copy code

public interface Parcelable 

{

    //Content description interface, basically don't care

    public int describeContents();

    //Write interface function, package

    public void writeToParcel(Parcel dest, int flags);

    //Read the interface, the purpose is to construct an instance processing of a class that implements Parcelable from Parcel. Because the implementation class is still unknown here, the template method needs to be used, and the inherited class name is passed in through the template parameter

    //In order to realize the input of template parameters, the Creator embedded interface is defined here, which contains two interface functions that return single and multiple inherited class instances respectively

    public interface Creator<T> 

    {

           public T createFromParcel(Parcel source);

           public T[] newArray(int size);

    }

}

copy code

7. Implement Parcelable steps

 

1)implements Parcelable

 

2) Rewrite the writeToParcel method to serialize your object into a Parcel object, that is: write the data of the class into the Parcel provided externally, package the data to be passed to the Parcel container for storage, so as to obtain data from the Parcel container

 

3) Rewrite the describeContents method, describe the content interface, and return 0 by default

 

4) Instantiate the static internal object CREATOR to implement the interface Parcelable.Creator

 

public static final Parcelable.Creator<T> CREATOR

Note: None of the public static finals can be missing, and the name of the internal object CREATOR cannot be changed, and must be all capitalized. Two methods in this interface need to be rewritten: createFromParcel(Parcel in) realizes reading and passing data values ​​from the Parcel container, encapsulates them into Parcelable objects and returns to the logic layer, and newArray(int size) creates a type of T and length of size Array, just one sentence (return new T[size]), used by external classes to deserialize arrays of this class.

 

In short: map your objects to Parcel objects via writeToParcel, and map the Parcel objects to your objects via createFromParcel. Parcel can also be regarded as a stream, the object is written into the stream through writeToParcel, and the object is read from the stream through createFromParcel, but this process needs to be implemented by you, so the order of writing and reading must be consistent.

 

code show as below:

 

copy code

public class MyParcelable implements Parcelable 

{

     private int mData;

 

     public int describeContents() 

     {

         return 0;

     }

 

     public void writeToParcel(Parcel out, int flags) 

     {

         out.writeInt(mData);

     }

 

     public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() 

     {

         public MyParcelable createFromParcel(Parcel in) 

         {

             return new MyParcelable(in);

         }

 

         public MyParcelable[] newArray(int size) 

         {

             return new MyParcelable[size];

         }

     };

     

     private MyParcelable(Parcel in) 

     {

         mData = in.readInt();

     }

 }

copy code

8. The difference between Serializable implementation and Parcelabel implementation

 

1) The implementation of Serializable only needs to implement Serializable. This just marks the object and the system will automatically serialize it.

 

2) The implementation of Parcelabel not only requires implements Parcelabel, but also needs to add a static member variable CREATOR to the class, which needs to implement the Parcelable.Creator interface.

 

Comparison of the two codes:

 

1) Create a Person class and implement Serializable

 

copy code

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;

    }

    

    public void setAge(int age)

    {

        this.age = age;

    }

}

copy code

2) Create a Book class and implement Parcelable

 

copy code

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

    }

}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326776275&siteId=291194637