Boris Duncan

About Boris Duncan

Tc Duncan is a senior developer in Hong Kong. He has 10 years of development experience. In recent year, he is engaged in mobile development.

Android Tutorial : Two methods of passing object by Intent (Serializable,Parcelable)

In this post, I will show you an simple example of how to pass object by intent in Android application. Parcelable and Serialization are used for marshaling and unmarshaling Java objects. In Parcelable, developers write custom code for marshaling and unmarshaling so it creates less garbage objects in comparison to Serialization. The performance of Parcelable over Serialization dramatically improves (around two times faster), because of this custom implementation.

Serialization is a marker interface, which implies the user cannot marshal the data according to their requirements. In Serialization, a marshaling operation is performed on a Java Virtual Machine (JVM) using the Java reflection API. This helps identify the Java objects member and behavior, but also ends up creating a lot of garbage objects. Due to this, the Serialization process is slow in comparison to Parcelable.

Step 1: main.xml for the layout

<?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="Hello Welcome to EasyInfoGeek."  
     />  
 <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>

Step 2: Create Person.java which implement serializable

package com.easyinfogeek.objectPass;  
 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;  
     }  

 }

Step 3: Create Book.java which implement Parcelable

package  com.easyinfogeek.objectPass;  
 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;  
     }  

     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);  
  parcel.writeString(author);  
  parcel.writeInt(publishTime);  
     }  
 }

Step 4: Create The ObjectPassDemo.java which is the main Activity class Create

2 more activity classes: ObjectPassDemo1.java use for display person ObjectPassDemo2.java use for display book

package com.easyinfogeek.objectPass;  
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.easyinfogeek.objectPass.ser";  
    public  final static String PAR_KEY = "com.easyinfogeek.objectPass.par";  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);     
        setupViews();  

    }  

    public void setupViews(){  
        sButton = (Button)findViewById(R.id.button1);  
        pButton = (Button)findViewById(R.id.button2);  
        sButton.setOnClickListener(this);  
        pButton.setOnClickListener(this);  
    }  

    public void SerializeMethod(){  
        Person mPerson = new Person();  
        mPerson.setName("Leon");  
        mPerson.setAge(25);  
        Intent mIntent = new Intent(this,ObjectTranDemo1.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putSerializable(SER_KEY,mPerson);  
        mIntent.putExtras(mBundle);  

        startActivity(mIntent);  
    }  

    public void PacelableMethod(){  
        Book mBook = new Book();  
        mBook.setBookName("Android Developer Guide");  
        mBook.setAuthor("Leon");  
        mBook.setPublishTime(2014);  
        Intent mIntent = new Intent(this,ObjectTranDemo2.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putParcelable(PAR_KEY, mBook);  
        mIntent.putExtras(mBundle);  

        startActivity(mIntent);  
    }  

    public void onClick(View v) {  
        if(v == sButton){  
            SerializeMethod();  
        }else{  
            PacelableMethod();  
        }  
    }  
}
package com.easyinfogeek.objectPass;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.widget.TextView;  
 public class ObjectPassDemo1 extends Activity {  
     @Override  
     public void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  

  TextView mTextView = new TextView(this);  
  Person mPerson = (Person)getIntent().getSerializableExtra(ObjectPassDemo.SER_KEY);  
  mTextView.setText("You name is: " + mPerson.getName() + "/n"+  
   "You age is: " + mPerson.getAge());  

  setContentView(mTextView);  
     }  
 }
package com.easyinfogeek.objectPass;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.widget.TextView;  
 public class ObjectPassDemo2 extends Activity {  

     public void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  TextView mTextView = new TextView(this);  
  Book mBook = (Book)getIntent().getParcelableExtra(ObjectPassDemo.PAR_KEY);  
  mTextView.setText("Book name is: " + mBook.getBookName()+"/n"+  
      "Author is: " + mBook.getAuthor() + "/n" +  
      "PublishTime is: " + mBook.getPublishTime());  
  setContentView(mTextView);  
     }  
 }

Step 5: Modify AndroidManifest.xml add the two acivityies

<?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=".ObjectPassDemo"  
     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=".ObjectPassDemo1"></activity>  
  <activity android:name=".ObjectPassDemo2"></activity>  
     </application>  
     <uses-sdk android:minSdkVersion="7" />  
 </manifest>

 

Related Whitepaper:

Rapid Android Development: Build Rich, Sensor-Based Applications with Processing

Create mobile apps for Android phones and tablets faster and more easily than you ever imagined

Use 'Processing', the free, award-winning, graphics-savvy language and development environment, to work with the touchscreens, hardware sensors, cameras, network transceivers, and other devices and software in the latest Android phones and tablets.

Get it Now!  

One Response to "Android Tutorial : Two methods of passing object by Intent (Serializable,Parcelable)"

  1. Robert says:

    Great article. Personally, I would use Serializable unless the object is really big in which case the speed difference would be visible by user.

    I also wonder what would be speed difference if we would implement Externalizable interface (and manually implement methods for reading and writing object) instead of Serializable.

Leave a Reply


× 9 = thirty six



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.