Serializable Parcelable two ways to pass objects in Android

  • 2021-01-03 21:05:18
  • OfStack

There are two ways to pass in Android, one is Serializable and the other is Parcelable.

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

2. Usage scenarios and differences:

1) When using memory, Parcelable performs better than Serializable, so Parcelable is recommended.

2) Serializable generates a large number of temporary variables during serialization, thus causing frequent GC.

3) Parcelable cannot be used in cases where data is to be stored on disk, because Parcelable does not do a good job of ensuring the persistence of data in case of external changes. Despite Serializable's low efficiency, Serializable is recommended at this time.

Serializable interface implementation is relatively simple, as long as the implementation of setter and getter, it is ok.

The Parcelable implementation is a bit trickier. Use 1 small demo to illustrate:

1. Create new android project ObjectTranDemo

2. Create an javaBean for entity: 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_ES53en.xml:


<?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="android object trance" 
/> 
<Button 
android:id="@+id/button1" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Serializable" 
/> 
<Button 
android:id="@+id/button2" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Parcelable" 
/> 
</LinearLayout>

4. Create Master activity. This activity is mainly used to respond to click events and pass 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; 
@Override 
protected 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); 
} 
@Override 
public void onClick(View v) { 
if(v == sButton){ 
SerializeMethod(); 
}else{ 
PacelableMethod(); 
} 
} 
}

5. Create activity ObjectTranDemo1.ES67en 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() + "\n"+ 
"You age is: " + mPerson.getAge()); 
setContentView(mTextView); 
} 
}

At this point, the Serializable interface passes the data, and don't forget to declare the new activity in the Mainfest.xml file


<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.objecttrandemo" 
android:versionCode="1" 
android:versionName="1.0" > 
<uses-sdk 
android:minSdkVersion="8" 
android:targetSdkVersion="18" /> 
<application 
android:allowBackup="true" 
android:icon="@drawable/ic_launcher" 
android:label="@string/app_name" 
android:theme="@style/AppTheme" > 
<activity 
android:name="com.example.objecttrandemo.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> 
</manifest>

Here's the transmission of Parcelable:

There are four steps to implementing Parcelable1:

1) implements Parcelable

2) Rewrite writeToParcel method to serialize your object into one Parcel object, that is: write the data of the class to the Parcel provided outside, package the data that needs to be passed to the Parcel container to save, in order to get the data from the Parcel container

3) Override describeContents method to describe the content interface and return 0 by default

4) Instantiate the static internal object CREATOR to implement the interface Parcelable.Creator

public static final Parcelable.Creator < T > CREATOR

Note: public static final1 cannot be reduced, and the name of the internal object CREATOR cannot be changed, it must be all uppercase. Two methods in this interface need to be overwritten: createFromParcel(Parcel in) implements reading passed data values from Parcel container, encapsulates Parcelable object return logic layer, and newArray(int size) creates an array of type T, length size, just one sentence (return new T[size]) for external class deserialization of this class array.

In short: writeToParcel maps your objects to Parcel objects, and Parcel maps your objects to createFromParcel. You can also think of Parcel as a stream in which objects are written to the stream by writeToParcel and objects are read from the stream by createFromParcel, but this process requires you to implement, so the order of writes and reads must be 1.

Specific:

1. Create the entity class of 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 
@Override 
public int describeContents() { 
return 0; 
} 
//give some attention to the oder betwwen writeToParcel and createFromParcel 
@Override 
public void writeToParcel(Parcel parcel, int flags){ 
parcel.writeString(bookName); 
parcel.writeString(author); 
parcel.writeInt(publishTime); 
} 
public static final Parcelable.Creator<Book> CREATOR = new Creator<Book>() { 
@Override 
public Book[] newArray(int size) { 
return new Book[size]; 
} 
@Override 
public Book createFromParcel(Parcel source) { 
Book mBook = new Book(); 
mBook.bookName = source.readString(); 
mBook.author = source.readString(); 
mBook.publishTime = source.readInt(); 
return mBook; 
} 
}; 
}

2. New activity :ObjectTranDemo2.java. Data used to display parcelable:


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()+"\n"+ 
"Author is: " + mBook.getAuthor() + "\n" + 
"PublishTime is: " + mBook.getPublishTime()); 
setContentView(mTextView); 
} 
}

In the last article, I introduced the difference between Serializable and Parcelable. If you are interested, please click here for details.


Related articles: