Two ways to transfer objects in Android (serializable,parcelable)

Source: Internet
Author: User

I believe that everyone in the process of Android development will always encounter in the middle of the activity to pass data, of course, encountered the need to pass the object in the intent of the situation is also unavoidable, so I took a bit of relevant knowledge, summarized here digest. For now, there are only two ways I know:

        1.利用Bundle.putSerializable(Key,Object);        2.利用Bundle.putParcelable(Key, Object);

The use and differences of the two methods are described in detail below.

First 1th, the premise of both approaches is to serialize the object being passed, so, what is the problem, what is serialization, how do we serialize, and what are the benefits of serialization? Here's a discussion of these issues:

# # # Serialization Meaning:
Serialization (serialization) transforms the state information of an object into a process that can be stored or transmitted in a form. During serialization, an object writes its current state to a temporary or persistent store. Later, the object can be recreated by reading or deserializing the state of the object from the store.

The purpose of serialization for # # #:
-Persistence of custom objects in some form of storage;
-Transfer objects from one place to another.
-Make the program more maintainable.

How to serialize

Two ways are described below:

    • Implement the Serializable interface (which is supported by the javase itself)
      -This kind of serialization is very simple, only need to implement a serializable interface can be implemented, specific reference code: Person Class
 PackageCom.create.studesreoger;Importjava.io.Serializable;/** * Created by 24540 on 2016/5/6. * * Public  class  person implements Serializable {    Private intIdPrivateString name; Public int getId() {returnId } Public void setId(intID) { This. id = ID; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; }}
    • The implementation of the Parcelable interface (which is unique to Android, is more efficient than implementing the Serializable interface, can be used for intent data transfer, or for interprocess communication (IPC)), which is a little more complicated, documenting the detailed steps:

1.implements parcelable
2. Override the Writetoparcel method to serialize the object to a parcel object, that is, to write the data of the class to an externally supplied parcel, to package the data that needs to be passed to the parcel container to save the data from the parcel container
3. Rewrite the Describecontents method, the Content interface description, the default return 0 is possible
4. Instantiate the static internal object Creator implementation interface Parcelable.creator

    • (PS) The interface description of the parcelable can refer to the official description,
      Interface for classes whose instances can is written to and restored from a Parcel. Classes implementing the Parcelable interface must also has a static field called CREATOR, which is an object Implementin G The Parcelable.creator interface.
      Official documentation There is also a good example of instantiation, which is useful for reference.
      If you use the Android studio2.1 version, then these things the compiler can do a good job for us to complete. Directly write out the properties of the class, add the Parcelable interface ALT + ENTER: will help us do this series of work, here we also put our code: Man class
 PackageCom.create.studesreoger;ImportAndroid.os.Parcel;Importandroid.os.Parcelable;/** * Created by 24540 on 2016/5/6. * * Public  class  man implements parcelable{    Private intIdPrivateString name;///With parameter constructor method is private, this constructor is only for class method Createfromparcel call    protected Mans(Parcel in)        {id = in.readint ();    Name = In.readstring (); }//Non-parametric construction method for the outside world to create an instance of the class is called     Public Mans() {    }//Save the attributes in the object to the target object dest    @Override     Public void Writetoparcel(Parcel dest,intFlags) {Dest.writeint (ID);    Dest.writestring (name); }@Override     Public int describecontents() {return 0; }//must create a constant named creator     Public Static FinalCreator<man> Creator =NewCreator<man> () {//Overrides the Createfromparcel method, creating and returning a user object that has obtained the data        @Override         PublicMansCreatefromparcel(Parcel in) {return NewMans (in); }@Override         PublicMan[]NewArray(intSize) {return NewMan[size]; }    }; Public int getId() {returnId } Public void setId(intID) { This. id = ID; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; }}
The difference between serializable implementation and Parcelabel implementation

1.Serializable implementation, only need implements Serializable.
The implementation of 2.Parcelabel requires not only implements Parcelabel, but also the addition of a static member variable Creator to the class, which requires the implementation of the Parcelable.creator interface.

Principles for choosing a serialization method
    • When using memory, parcelable is better than serializable, so it is recommended to use parcelable.
    • Serializable generates a large number of temporary variables at serialization time, resulting in frequent GC.
    • Parcelable cannot be used in situations where data is stored on disk, because Parcelable does not guarantee the continuity of the data in the event of external change. Although serializable is inefficient, it is recommended to use serializable at this point.
    • It is necessary to pass some data between multiple parts (activity or service) through intent, and simple types (such as numbers, strings) can be placed directly into intent. Complex types must implement the Parcelable interface.

    • The following is the implementation of the object is passed and received, relatively simple, directly on the code:
      Here we are implementing a well-serialized object in Mainactivity (including the previous two methods)

 PackageCom.create.studesreoger;ImportAndroid.content.Intent;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View; Public  class mainactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);    Setcontentview (R.layout.activity_main); }//Passing objects in serializable mode     Public void sendforserializable(View view) {Person person =NewPerson (); Person.setid ( -); Person.setname ("AM"); Intent Intent =NewIntent ( This, Nextacitvity.class); Bundle bundle =NewBundle (); Bundle.putserializable ("Serializable", person);        Intent.putextras (bundle);    StartActivity (Intent); }//Passing objects in parcelable mode     Public void sendforparcelable(View view) {Man mans =NewMan (); Man.setid (10010); Man.setname ("Testparcelable"); Bundle bundle =NewBundle (); Bundle.putparcelable ("Parcelable", man); Intent Intent =NewIntent ( This, Nextacitvity.class);        Intent.putextras (bundle);    StartActivity (Intent); }}

Then we need to receive the object's nexacitvity, where we implement the Get object instance

 PackageCom.create.studesreoger;ImportAndroid.content.Intent;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.widget.EditText; Public  class nextacitvity extends appcompatactivity {    PrivateEditText EditText1;PrivateEditText editText2;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.layout_next);//Get the object that is passed by serializable and display it .EditText1 = (EditText) Findviewbyid (R.ID.TEXT1); Person person = (person) getintent (). Getserializableextra ("Serializable");if(Person! =NULL) {Edittext1.settext ("id ="+person.getid () +"****"+"The name is:"+person.getname ()); }//Get the object that is passed by getparcelable and display it .EditText2 = (EditText) Findviewbyid (R.ID.TEXT2);        Intent Intent2 = Getintent ();        Bundle bundle = Intent2.getextras (); Mans man = bundle.getparcelable ("Parcelable");if(Man! =NULL) {Edittext2.settext ("id ="+man.getid () +"****"+"The name is:"+man.getname ()); }    }}
    • Finally, attach the XML file source code:
      Layout_next.xml Layout File Source code
 <?xml version= "1.0" encoding= "Utf-8"?><linearlayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  android:layout_width  =" match_parent " android:layout_height  =" match_parent " android:orientation  =;     <edittext  android:layout _width  = "match_parent"  android:layout_height  = "wrap_content"  android:id  = "@+id/text1"  android:layout_weight  =" 1 " android:text  =" I'm the object of the Serserializable transfer unit. "/>     <EditTextandroid:layout_width="Match_parent"android:layout_height= "Wrap_content" android:id="@+id/text2"android:layout_weight="1"android:text= "I am the object of the Parcelable transfer unit" />                                        </linearlayout>

Activity_main.xml the source code of the main layout file

<?xml version= "1.0" encoding= "Utf-8"?><Relativelayout xmlns:android="Http://schemas.android.com/apk/res/android"    Xmlns:tools="Http://schemas.android.com/tools"    Android:layout_width="Match_parent"    Android:layout_height="Match_parent"    Android:paddingbottom="@dimen/activity_vertical_margin"    Android:paddingleft="@dimen/activity_horizontal_margin"    Android:paddingright="@dimen/activity_horizontal_margin"    Android:paddingtop="@dimen/activity_vertical_margin"    Tools:context="Com.create.studesreoger.MainActivity">    <buttonandroid:layout_width="Match_parent"android:layout_height= "Wrap_content" Android:text="Pass the object with serializable!" Android:onclick="sendforserializable"/>                                    <buttonandroid:layout_alignparentbottom="true"android:layout_width= "Match_parent" android:layout_height="Wrap_content"android:text="Pass the object with Parcelable!" Android:onclick="sendforparcelable"/>                                        </relativelayout>

-Finally, when the program runs, you need to declare the acivity we added in the Androidmanifest file

```<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android"  package ="Com.create.studesreoger">        <applicationandroid:allowbackup="true"android:icon="@mipmap/ Ic_launcher "android:label=" @string/app_name "android:supportsrtl=" True "android:theme=" @style/apptheme ">                                                <activity android:name=". Mainactivity ">            <intent-filter>                <action android:name="Android.intent.action.MAIN" />                <category android:name="Android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=". Nextacitvity "></activity>    </Application></manifest>

Results
! [Enter description here] [1]

Two ways to transfer objects 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.