This article is reprinted from

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. Realization Parcelable Just for serialization , that , Why serialize ?

1) Keep objects permanently , Save the byte sequence of the object to the local file ;

2) Passing objects through the network by serializing them ;

3) Passing objects between processes through serialization .

3. How to realize serialization

Android There are two options for implementing serialization in : One is to realize Serializable Interface ( yes JavaSE It's supported by itself ), One is to realize Parcelable Interface ( yes Android Unique features , Efficiency is better than achievement Serializable Efficient interface , Can be used for Intent Data transfer , It can also be used for interprocess communication (IPC)). Realization Serializable The interface is very simple , Just make a statement , To achieve Parcelable The interface is a little more complicated , But it's more efficient , This method is recommended to improve performance .

notes :Android in Intent There are two ways to pass objects : One is Bundle.putSerializable(Key,Object), The other is Bundle.putParcelable(Key,Object). Of course these Object There are certain conditions , The former is realized Serializable Interface , The latter is realized Parcelable Interface .

4. The principle of choosing serialization methods

1) When using memory ,Parcelable Than Serializable High performance , Therefore, it is recommended to use Parcelable.

2)Serializable A large number of temporary variables will be generated during serialization , So as to cause frequent GC.

3)Parcelable Can not be used in the case of data to be stored on disk , because Parcelable It can't guarantee the continuity of data in case of external changes . Even though Serializable Low efficiency , However, it is recommended to use Serializable .

5. Application scenarios

It needs to be in multiple parts (Activity or Service) Through between Intent Pass some data , Simple type ( Such as : Numbers 、 character string ) You can put it directly into Intent. Complex types must implement Parcelable Interface .

6Parcelable Interface definition

public interface Parcelable
// Content description interface , It doesn't matter
public int describeContents();
// Write interface functions , pack
public void writeToParcel(Parcel dest, int flags);
// Read interface , The aim is to start with Parcel Construct an implementation in Parcelable Instance processing of class . Because the implementation class is still unknown here , So you need to use templates , The inherited class name is passed in through the template parameter
// In order to pass in template parameters , Defined here Creator Embedded interface , Contains two interface functions that return single and multiple instances of inheritance classes
public interface Creator<T>
public T createFromParcel(Parcel source);
public T[] newArray(int size);

7、 Realization Parcelable step

1)implements Parcelable

2) rewrite writeToParcel Method , Serialize your object into a Parcel object , namely : Write the data of the class to the externally provided Parcel in , Package the data that needs to be delivered to Parcel Containers keep , So that Parcel Containers get data

3) rewrite describeContents Method , Content interface description , Default return 0 Can

4) Instantiate static internal objects CREATOR Implementation interface Parcelable.Creator

public static final Parcelable.Creator<T> CREATOR

notes : among public static final Not one less , Internal object CREATOR You can't change the name of , It has to be all in capitals . Two methods in this interface need to be rewritten :createFromParcel(Parcel in) from Parcel Read the pass data value in the container , Encapsulated into Parcelable Object returns to the logical layer ,newArray(int size) Create a type of T, The length is size Array of , Just one sentence (return new T[size]), For external class deserialization of this class array use .

In short : adopt writeToParcel Map your object to Parcel object , Re pass createFromParcel take Parcel Objects map to your objects . Can also be Parcel See it as a stream , adopt writeToParcel Write objects into the stream , Through createFromParcel Reading objects from the stream , It's just that this process needs you to do , So the order of writing and the order of reading must be the same .

The code is as follows :

public class MyParcelable implements Parcelable 
private int mData; public int describeContents()
return 0;
} public void writeToParcel(Parcel out, int flags)
} 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();

8Serializable Realization and Parcelabel The difference of realization

1)Serializable The implementation of the , It only needs implements  Serializable that will do . It's just a marker for the object , The system will automatically serialize it .

2)Parcelabel The implementation of the , Not only need implements  Parcelabel, You also need to add a static member variable to the class CREATOR, This variable needs to be implemented Parcelable.Creator Interface .

Compare the two codes :

1) establish Person class , Realization Serializable

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)
{ = name;
} public int getAge()
return age;
} public void setAge(int age)
this.age = age;

2) establish Book class , Realization Parcelable

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)
{ = 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)
} public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>()
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();

Android Of Parcelable More articles on interfaces

  1. Android in Parcelable Interface usage

    from: Interface for classes wh ...

  2. Android in Parcelable Use of interfaces

    In the process of development , Serialization is very common . For example, you need to save the object to the local disk or upload it on the network . There are two ways to achieve serialization , One is to realize Serializable Interface , The second is to realize Parcelable. Serializab ...

  3. Android in Parcelable Interface

    1. Parcelable Interface Interface for classes whose instances can be written to and restored from a Parcel. ...

  4. ( turn )Android in Parcelable Interface usage

    1. Parcelable Interface Interface for classes whose instances can be written to and restored from a Parcel. ...

  5. Android in Parcelable And Serializable Interface usage

    from : Android in Parcelable Interface usage 1. Parcelable Interface Interface for classes whose instances can be written to a ...

  6. Android Call remote Service The parameters and return values of need to be implemented Parcelable Interface

    import android.os.Parcel;import android.os.Parcelable; public class Person implements Parcelable{ pr ...

  7. Android Studio Cool plug in ( One )—— Automation is fast Parcelable Interface serialization One . Foreword believe that data serialization, we are more or less exposed to , For example, an entity class is customized , Need to be in activit ...

  8. Android in Parcelable and Serializable Interface usage

    1. Parcelable Interface Interface for classes whose instances can be written to and restored from a Parcel. ...

  9. Android In the system Parcelable and Serializable The difference between , Automation Parcelable Interface plug-ins

    Parcelable and Serializable The difference between Reference address : Because of the final zone ...

Random recommendation

  1. SilverFoxServer Baked !!

    SilverFoxServer What is it ? Let's have a look SmartFoxServer Know it easily It's a set of server + Client communication framework , Set up the turn system quickly , Chess and card online Webpage game SilverFoxServer Features include use ...

  2. Guava 12- Mathematical operations

    Example int logFloor = LongMath.log2(n, FLOOR); int mustNotOverflow = IntMath.checkedMultiply(x, y); long ...

  3. YUV Pixels and ycbcr

    What are the basic elements of a color image ? To put it bluntly , The basic thing that an image contains is binary data , Its capacity is the number of binary data in essence . A picture 1920x1080 Pixel YUV422 Image , Size is 1920X1080X2=4147 ...

  4. UIView attribute clipsTobounds Application

    view add to view, And cut the edge (UIView attribute clipsTobounds Application ) As the title , There are two view: view1,view2 view1 add to view2 To which , If view2 Greater than view1, perhaps vi ...

  5. PPTP Protocol handshake process analysis

    One  PPTP summary PPTP(Point to Point Tunneling Protocol), Point to point tunneling protocol . The agreement is in PPP A new enhanced security protocol is developed based on the protocol , Support multi protocol virtual private network , can ...

  6. Python Third articles ( Next ):collections series 、 aggregate (set)、 Single and double queues 、 depth copy、 Built in functions

      One .collections series : collections It's actually python The standard library of , That is to say python A built-in module for , So import it before you use it collections The module can ,collections stay py ...

  7. pyspider+PhantomJS Proxy settings for

    Environmental Science :pyspider0.3.9 PhantomJS2.1.1, It's the latest edition of For process supervisor managed . There are several places that need to be added : webui process : pyspider -c config.json ...

  8. C++ Three ways to create objects

    I used to confuse myself a lot A a(1); Stack memory allocation A b = A(1); Stack memory allocation , There is no essential difference from the first one A c = new A(1); Heap memory allocation The first two are released after the function body is executed , The third need ...

  9. linux The foundation grep

    grep: Global search REgular expression and Print out the line effect : Text search tools , Match the target text line by line according to the user specified pattern , Print match ...

  10. tensorflow relevant API Learning from

    Study Directory 1.tensorflow Correlation function understanding (1)tf.nn.conv2d (2)tf.nn.relu (3)tf.nn.max_pool (4)tf.nn.dropout (5) ...