Android master path: Serializable and Parcelable, two methods of Intent passing objects in Android

Source: Internet
Author: User

Android master path: Serializable and Parcelable, two methods of Intent passing objects in Android

 

In Android, two methods are passed: Serializable and Parcelable.

Serializable is supported by J2SE. Parcelable is unique to Android.

Use Cases and differences:

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, resulting in frequent GC.


3) Parcelable cannot be used when you want to store data on a disk, because Parcelable cannot guarantee data continuity in the case of external changes. Although the Serializable efficiency is low, we recommend using Serializable.

 

The Serializable interface is easy to implement. You only need to implement setter and getter.

The implementation of Parcelable is more troublesome. Use a small demo to describe:

1. Create an android project ObjectTranDemo

2. Create an entity javaBean: Person. java. Implement the Serializable interface.

 

package com.example.objecttrandemo;import java.io.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) {          this.name = name;      }      public int getAge() {          return age;      }      public void setAge(int age) {          this.age = age;      }        }  

3. Create the main interface activity_main.xml:

 

 

 
 
  
   
   
  
 

4. Create a primary activity. This activity is mainly used to respond to click events and transmit data. ObjecttranDemo. java:

 

 

package com.example.objecttrandemo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class ObjectTranDemo extends Activity implements OnClickListener{private Button sButton,pButton;  @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);setupViews();  }//initial the views    public void setupViews(){          sButton = (Button)findViewById(R.id.button1);          pButton = (Button)findViewById(R.id.button2);          sButton.setOnClickListener(this);          pButton.setOnClickListener(this);      }         //Serializeable object trance     public void SerializeMethod(){    Person mPerson = new Person();     mPerson.setName(durant);     mPerson.setAge(25);     Intent mIntent = new Intent(this,ObjectTranDemo1.class);    Bundle mBundle = new Bundle();      mBundle.putSerializable(mPerson,mPerson);      mIntent.putExtras(mBundle);    startActivity(mIntent);      }        //Pacelable object trance      public void PacelableMethod(){    Book mBook = new Book();    mBook.setBookName(a man from mars);      mBook.setAuthor(james);    mBook.setPublishTime(2014);    Intent mIntent = new Intent(this,ObjectTranDemo2.class);      Bundle mBundle = new Bundle();     mBundle.putParcelable(mBook, mBook);      mIntent.putExtras(mBundle);      startActivity(mIntent);      }@Overridepublic void onClick(View v) {if(v == sButton){              SerializeMethod();          }else{              PacelableMethod();          }}  }

5. Create an activity ObjectTranDemo1.java to display the data passed by the Serializable interface.

 

 

package com.example.objecttrandemo;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class ObjectTranDemo1 extends Activity{ @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);                    TextView mTextView = new TextView(this);          Person mPerson = (Person)getIntent().getSerializableExtra(mPerson);          mTextView.setText(You name is:  + mPerson.getName() + +                  You age is:  + mPerson.getAge());                    setContentView(mTextView);      }  }

At this point, the Serializable interface has passed data. By the way, do not forget to declare the new activity in the Mainfest. xml file.

 

 

 
     
                          
                                   
                
    
                                   
  
 

The following describes the transmission of Parcelable:

 

It generally takes four steps to implement Parcelable:

1) implements Parcelable


2) rewrite the writeToParcel method to serialize your object into a Parcel object, that is, write the data of the class to the external provided Parcel, and package the data to be transferred to the Parcel container for storage, to get data from the Parcel container


3) override the describeContents method and content interface description. By default, 0 is returned.


4) instantiate static internal Object CREATOR implementation interface Parcelable. Creator


Public static final Parcelable. Creator CREATOR
Note: either public static final or internal Object CREATOR cannot be changed. The names must be capitalized. You need to override the two methods in this interface: createFromParcel (Parcel in) to read and pass data values from the Parcel container, encapsulate them into Parcelable objects and return to the logic layer, newArray (int size) create an array of T type and size. return new T [size] in only one sentence for external class deserialization.


In short, you can map your object to a Parcel object through writeToParcel, and then map the Parcel object to your object through createFromParcel. You can also regard Parcel as a stream, write the object to the stream through writeToParcel, and read the object from the stream through createFromParcel, but you need to implement this process, therefore, the write sequence must be consistent with the read sequence.

Details:

1. Create an object class for the Book:

Book. java:

 

package com.example.objecttrandemo;import android.os.Parcel;import android.os.Parcelable;public class Book implements Parcelable{private String bookName;  private String author;  private int publishTime;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 getPublishTime() {return publishTime;}public void setPublishTime(int publishTime) {this.publishTime = publishTime;}  //Internal Description Interface,You do not need to manage@Overridepublic int describeContents() {return 0;} //give some attention to the oder betwwen  writeToParcel and createFromParcel@Overridepublic void writeToParcel(Parcel parcel, int flags){parcel.writeString(bookName);parcel.writeString(author);parcel.writeInt(publishTime);}public static final Parcelable.Creator
 
   CREATOR = new Creator
  
   () {@Overridepublic Book[] newArray(int size) {return new Book[size];}@Overridepublic Book createFromParcel(Parcel source) {Book mBook = new Book();  mBook.bookName = source.readString(); mBook.author = source.readString();  mBook.publishTime = source.readInt(); return mBook;}};    }
  
 
2. Create activity: ObjectTranDemo2.java. To display parcelable data:

 

 

package com.example.objecttrandemo;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class ObjectTranDemo2 extends Activity{ public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          TextView mTextView = new TextView(this);          Book mBook = (Book)getIntent().getParcelableExtra(mBook);          mTextView.setText(Book name is:  + mBook.getBookName()++                            Author is:  + mBook.getAuthor() +  +                            PublishTime is:  + mBook.getPublishTime());          setContentView(mTextView);      } }


 

 

 


 

 

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.