Difference between Serializable and Parcelable in Android?

Both are used to support serialization and deserialization operations. The biggest difference between the two is the difference in storage media. Serializable uses IO to read and write storage on the hard disk, while Parcelable reads and writes directly in memory. Obviously, the memory The read and write speed of IO is usually greater than that of IO, so Parcelable is usually preferred in Android.
Serializable is not the current focus, but you can see a simple example of Serializable implemented in the article "Analysis of Java Serialization Algorithms", view the IO files generated by serialization, and read in hexadecimal and explain each 16 one by one The meaning of the base number.

 

Parcelable example:

 

public class MyParcelable implements Parcelable {  
     private int mData;  
     private String mStr;  
  
     public int describeContents() {  
         return 0;  
     }  
  
     // write data to save  
     public void writeToParcel(Parcel out, int flags) {  
         out.writeInt(mData);  
         out.writeString(mStr);  
     }  
  
     // object used to create custom Parcelable  
     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];  
         }  
     };  
       
     // read data for recovery  
     private MyParcelable(Parcel in) {  
         mData = in.readInt();  
         mStr = in.readString();  
     }  
 }  

 

 

   

//Pacelable pass object method  
    public void PacelableMethod () {  
        Book mBook = new Book();  
        mBook.setBookName("Android Tutor");  
        mBook.setAuthor("Frankie");  
        mBook.setPublishTime(2010);  
        Intent mIntent = new Intent(this,ObjectTranDemo2.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putParcelable(PAR_KEY, mBook);  
        mIntent.putExtras (mBundle);  
          
        startActivity (mIntent);  
    }  

 

 

If the element is a list, you need to pass in a new ArrayList first, otherwise a null pointer exception will be reported. as follows:

list = new ArrayList<String>();

in.readStringList(list);

 

 

 

 

//Serializeable method of passing objects  
    public void SerializeMethod(){  
        Person mPerson = new Person();  
        mPerson.setName("frankie");  
        mPerson.setAge(25);  
        Intent mIntent = new Intent(this,ObjectTranDemo1.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putSerializable(SER_KEY,mPerson);  
        mIntent.putExtras (mBundle);  
          
        startActivity (mIntent);  
    }  

 

Guess you like

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