All CategoriesAndroid App Development

Introduction to Serializable & Parcelable

Introduction:
Serializable and Parcelable are two interfaces, where Serializable is a standard java interface and Parcelable is an Android-specific interfaceSerializable interface implemented by “java.io.Serializable” and Parcelable interface by “android.os.Parcelable”.
In Android, if we want to pass the objects to activities then there is a need to implement the Serializable or Parcelable interface.
Serializable interface is easy to implement by overriding the methods but it is a slow process and it creates a lot of temporary objects and causes quite a bit of garbage collection.
Parcelable interface takes more time to implement in comparison to Serializable because of the code size. But it performs faster than Serializable and use fewer resources.
Let’s do it with the help of Example.
Example with code:
Here in this Example, we implement the Serializable and the Parcelable interface both for passing the objects in activities.

  1. Create an Application and name it AndroidSerializableAndParcelableExample.

Requirements:
Person.java -> This class implements a Serializable interface.
Book.java -> This class implements a Parcelable interface and its overridden methods.
ObjectPassingActivity -> This is our Main activity where we pass the objects in different activities.
GetObjectSerializableActivity -> Here we get the object by Serializable.
GetObjectParcelableActivity -> Here we get the object by Parcelable.
object_passing_activity.xml -> This is our main layout file.
Let’s do it one by one.
Person.java:
Add the code
Create class Person in your application and implement the Serializable interface

public class Person implements Serializable {
	private static final long serialVersionUID = 1L;
	private String name;
	private int age;
// setters and getters
}

Book.java:
Add the code
Create class Book and implement Parcelable interface and its methods.

public class Book implements Parcelable {
	private String bookName;
	private String author;
	private int publishTime;
	// setters and getters

Inside this create a constant for our class having static field called CREATOR which calls a constructor and returns the new object.

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];
		}
	};

Inside this class Override the methods describeContents() and writeToParcel(…)
In writeToParcel(…) method we write the values to save parcel.

public int describeContents() {
		return 0;
	}
	public void writeToParcel(Parcel parcel, int flags) {
		parcel.writeString(bookName);
		parcel.writeString(author);
		parcel.writeInt(publishTime);
	}

object_passing_activity.xml:
Add the code
Create an XML file with two buttons one for passing object by the Serializable method and another for Parcelable.

<Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="20dp"
        android:background="#8A2BE2"
        android:text="Serializable" />
    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="#8A2BE2"
        android:text="Parcelable" />

ObjectPassingActivity.java:
Add the code
Here we initialize the keys and Buttons like

private Button sButton,pButton;
public  final static String SER_KEY = "com.example.androidserializableandparcelableexample.ser";
public  final static String PAR_KEY = "com.example.androidserializableandparcelableexample.par";

Take the reference of buttons and set click listeners on them in onCreate(..)
Add the code in onCreate(…){}

sButton = (Button)findViewById(R.id.button1);
pButton = (Button)findViewById(R.id.button2);
sButton.setOnClickListener(this);
pButton.setOnClickListener(this);

On clicking Serialize button we pass the object like

Person mPerson = new Person();
        mPerson.setName("Harry");
        mPerson.setAge(20);
        Intent mIntent = new Intent(this,GetObjectSerializableActivity.class);
        Bundle mBundle = new Bundle();
        mBundle.putSerializable(SER_KEY,mPerson);
        mIntent.putExtras(mBundle);
        startActivity(mIntent);

Here we pass the Person object with a unique key by intent using the Serializable method.
Next, on clicking Parcelable button we pass the object like

Book mBook = new Book();
        mBook.setBookName("Pro Android Media");
        mBook.setAuthor("Shawn Van Every");
        mBook.setPublishTime(2009);
        Intent mIntent = new Intent(this,GetObjectParcelableActivity.class);
        Bundle mBundle = new Bundle();
        mBundle.putParcelable(PAR_KEY, mBook);
        mIntent.putExtras(mBundle);
        startActivity(mIntent);

Here we pass the Book object with a unique key by intent using a Parcelable method.
Now, it is time to get the object in different activities.
GetObjectSerializableActivity.java:
Add the code in onCreate(){}

Person mPerson = (Person)getIntent().getSerializableExtra(ObjectPassingActivity.SER_KEY);
		mTextView.setText("Your name is: " + mPerson.getName() + "\n"+
				"Your age is: " + mPerson.getAge());

Here we get the object with the same key by using a Serializable method.
GetObjectParcelableActivity.java:
Add the code in onCreate(){}
Same as here we get the object using a unique key by using a Parcelable method.

Book mBook = (Book)getIntent().getParcelableExtra(ObjectPassingActivity.PAR_KEY);
		mTextView.setText("Book name is: " + mBook.getBookName()+"\n"+
				"Author is: " + mBook.getAuthor() + "\n" +
				"Publish Time is: " + mBook.getPublishTime());

Conclusion:
So, these are the basic requirements to pass the objects by using a Serializable or Parcelable interface. Serializable is easy to implement but we prefer Parcelable interface because it is efficient, faster and android specific in comparison to Serializable.
Output
 

 

For more info click here.

Android Programming

Tags

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close