Go Two ways to pass objects intent in Android (Serializable,parcelable)

Source: Internet
Author: User

http://blog.csdn.net/xyz_lmn/article/details/5908355

Today I would like to tell you how to transfer objects in Android intent, as far as I know there are two ways, one is bundle.putserializable (Key,object), the other is bundle.putparcelable ( Key, object); Of course, these objects are certain conditions, the former is the implementation of the serializable interface, and the latter is the implementation of the Parcelable interface, in order to make it easier for everyone to understand I still write a simple demo, everyone step by step with me!

The first step: Create a new Android project named Objecttrandemo (more than the class Oh!) Directory structure such as:

Step Two: Modify the Main.xml layout file (I added two buttons here) code as follows

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:orientation=" vertical "    android:layout_width=" fill_parent "    android:layout_height=" Fill_parent "    ><textview      android:layout_width=" fill_parent "     android:layout_height=" Wrap_ Content "     android:text=" Welcome to Mr Wei ' s blog. "    /><buttonandroid:id= "@+id/button1" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:text= "Serializable"/><buttonandroid:id= "@+id/button2" android:layout_width= "Fill_parent" Android: layout_height= "Wrap_content" android:text= "parcelable"/></linearlayout>

  

Step three: Create a new two class one is Person.java implementation serializable interface, another Book.java implement Parcelable interface, the code is as follows:

Person.java:

Package Com.tutor.objecttran;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.) {this.age = age;}}

Book.java:

Package Com.tutor.objecttran;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 boo Kname;} 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;} public static final parcelable.creator<book> Creator = new creator<book> () {Public book Createfromparcel ( Parcel source) {Book Mbook = new book (); mbook.bookname = Source.readstring (); mbook.author = Source.readstring (); Mbook.publishtime = Source.readint (); return mbook;} Public book[] NewArray (int size) {return new book[size];}; public int describecontents () {return 0;} public void Writetoparcel (Parcel Parcel, int flags) {parcel.writestring (bookname);p ARcel.writestring (author);p Arcel.writeint (Publishtime);}} 

  

Fourth step: Modify Objecttrandemo.java, and create two new activity, one is Objecttrandemo1.java, The other one is Objecttrandemo2.java. Used to display person-to-image data, and book object data: The code is as follows:

Objecttrandemo.java:

Package Com.tutor.objecttran;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;public final static String    Ser_key = "Com.tutor.objecttran.ser";p ublic final static String Par_key = "Com.tutor.objecttran.par";        public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);           Setcontentview (R.layout.main);            Setupviews ();    }//I have always been the style of hehe public void setupviews () {Sbutton = (Button) Findviewbyid (R.id.button1);    Pbutton = (Button) Findviewbyid (R.id.button2);    Sbutton.setonclicklistener (this);    Pbutton.setonclicklistener (this);    //serializeable the method of passing the object 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);    }//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); }//Ammonium button Click event Response public void OnClick (View v) {if (v = = Sbutton) {Serializemethod ();} Else{pacelablemethod ();}}}

Objecttrandemo1.java:

Package Com.tutor.objecttran;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 (Objecttrandemo.ser_key);        Mtextview.settext ("You name is:" + mperson.getname () + "/n" + "You are        :" + mperson.getage ());                Setcontentview (Mtextview);    }}

Objecttrandemo2.java:

Package Com.tutor.objecttran;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 (Objecttrandemo.par_key);        Mtextview.settext ("Book Name is:" + mbook.getbookname () + "/n" +          "Author is:" + mbook.getauthor () + "/n" +          "Publish Time is: "+ mbook.getpublishtime ());        Setcontentview (Mtextview);    }}

Fifth step: A more important step, modify the Androidmanifest.xml file (two new ACTIVITY,OBJECTTRANDEMO1,OBJECTTRANDEMO2) to declare the code as follows (14th, 15 lines):

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "      package=" Com.tutor.objecttran "      android:versioncode=" 1 "      android:versionname=" 1.0 ">    <application android:icon= "@drawable/icon" android:label= "@string/app_name" >        <activity android:name= ". Objecttrandemo "                  android:label=" @string/app_name ">            <intent-filter>                <action android:name= "Android.intent.action.MAIN"/>                <category android:name= "Android.intent.category.LAUNCHER"/>            </intent-filter>        </activity><activity android:name= ". ObjectTranDemo1 "></activity><activity android:name=". ObjectTranDemo2 "></activity>    </application>    

  

Sixth step: Run the above project to see:

Effect 1: First interface:

Effect 2: Click the Serializable button

Effect 3: Click the parcelable button:

Ok~ to come here today, if you want to too long code, do not want to knock, you can leave an email. I send you the past, hehe ~ hope to everyone a little help, bye~

Go Two ways to pass objects intent in Android (Serializable,parcelable)

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.