Android Parcelable Example – Passing data between activities

May 16, 2013
By

Parcel is a serialization mechanism provided by Android. In order to write an object to a Parcel, that object should implement the interface “Parcelable“.

In this article, we will see how to implement a Parcelable object in an Android application to pass complex data from one activity to another activity.



In order to define a custom parcelable class, we need to implement the interface Parcelable in the class and it must override the methods “describeContents()” and “writeToParcel(Parcel dest, int flags)“. ┬áIt is also necessary to create a public static member variable “CREATOR” that should implement the interface “Parcelable.Creator<T>“.

This application is developed in Eclipse (4.2.1) with ADT plugin (21.1.0) and Android SDK (21.1.0).



1. Create a new Android application project namely “ParcelObjectDemo”

Create application project namely "ParcelObjectDemo"

Figure 1 : Create application project namely "ParcelObjectDemo"


2. Configure the project

Configure the application project

Figure 2 : Configure the application project


3. Design application launcher icon

Design application launcher icon

Figure 3 : Design application launcher icon


4. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


5. Enter MainActivity details

Enter MainActivity details

Figure 5 : Enter MainActivity details


6. Remove Android Support Library from this project

Since this application does not require Android support library, we can remove the library from this project if it is already added by the Eclipse IDE in the folder “libs”.


7. Update the file res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Parcelable Example</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="str_hnt_sname">Student Name</string>
    <string name="str_hnt_saddress">Student Address</string>
    <string name="str_hnt_scourse">Student Course</string>
    <string name="str_hnt_sage">Student Age</string>
    <string name="str_btn_ok">OK</string>
</resources>


8. Update the layout file res/layout/activity_main.xml


<LinearLayout 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"
    tools:context=".MainActivity"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/et_sname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/str_hnt_sname"/>

    <EditText
        android:id="@+id/et_sage"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:hint="@string/str_hnt_sage"/>

    <EditText
        android:id="@+id/et_saddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/str_hnt_saddress"/>

    <EditText
        android:id="@+id/et_scource"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/str_hnt_scourse"/>

    <Button
        android:id="@+id/btn_ok"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_ok" />

</LinearLayout>


9. Create a layout file res/layout/activity_student.xml


<?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="vertical" >

    <TextView
        android:id="@+id/tv_sname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/tv_sage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/tv_saddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/tv_scourse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textIsSelectable="true" />

</LinearLayout>


10. Create a Parcelable class in the file src/in/wptrafficanalyzer/parcelobjectdemo/Student.java


package in.wptrafficanalyzer.parcelobjectdemo;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

public class Student implements Parcelable{

    String mSName;
    int mSAge;
    String mSAddress;
    String mSCourse;

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    /**
    * Storing the Student data to Parcel object
    **/
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mSName);
        dest.writeInt(mSAge);
        dest.writeString(mSAddress);
        dest.writeString(mSCourse);
    }

    /**
    * A constructor that initializes the Student object
    **/
    public Student(String sName, int sAge, String sAddress, String sCourse){
        this.mSName = sName;
        this.mSAge = sAge;
        this.mSAddress = sAddress;
        this.mSCourse = sCourse;
    }

    /**
    * Retrieving Student data from Parcel object
    * This constructor is invoked by the method createFromParcel(Parcel source) of
    * the object CREATOR
    **/
    private Student(Parcel in){
        this.mSName = in.readString();
        this.mSAge = in.readInt();
        this.mSAddress = in.readString();
        this.mSCourse = in.readString();
    }

    public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {

        @Override
        public Student createFromParcel(Parcel source) {
            return new Student(source);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };
}


11. Create an activity class in the file src/in/wptrafficanalyzer/parcelobjectdemo/StudentViewActivity.java


package in.wptrafficanalyzer.parcelobjectdemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class StudentViewActivity extends Activity {

    TextView mTvSName;
    TextView mTvSAge;
    TextView mTvSAddress;
    TextView mTvSCourse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student);

        // Fetching data from a parcelable object passed from MainActivity
        Student student = getIntent().getParcelableExtra("student");

        // Getting reference to TextView tv_sname of the layout file activity_student
        mTvSName = (TextView)findViewById(R.id.tv_sname);

        // Getting reference to TextView tv_sage of the layout file activity_student
        mTvSAge = (TextView) findViewById(R.id.tv_sage);

        // Getting reference to TextView tv_saddress of the layout file activity_student
        mTvSAddress = (TextView) findViewById(R.id.tv_saddress);

        // Getting reference to TextView tv_scourse of the layout file activity_student
        mTvSCourse = (TextView) findViewById(R.id.tv_scourse);

        if(student!=null){
            mTvSName.setText("Name:"+student.mSName);
            mTvSAge.setText("Age:"+Integer.toString(student.mSAge));
            mTvSAddress.setText("Address:"+student.mSAddress);
            mTvSCourse.setText("Course:"+student.mSCourse);
        }
    }
}


12. Update the activity class “MainActivity” in the file src/in/wptrafficanalyzer/parcelobjectdemo/MainActivity.java


package in.wptrafficanalyzer.parcelobjectdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

    EditText mEtSName;
    EditText mEtSAge;
    EditText mEtSAddress;
    EditText mEtSCourse;
    Button mBtnOk;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting a reference to EditText et_sname of the layout activity_main
        mEtSName = (EditText)findViewById(R.id.et_sname);

        // Getting a reference to EditText et_sage of the layout activity_main
        mEtSAge = (EditText)findViewById(R.id.et_sage);

        // Getting a reference to EditText et_saddres of the layout activity_main
        mEtSAddress = (EditText)findViewById(R.id.et_saddress);

        // Getting a reference to EditText et_scourse of the layout activity_main
        mEtSCourse = (EditText)findViewById(R.id.et_scource);

        // Getting a reference to Button btn_ok of the layout activity_main
        mBtnOk = (Button)findViewById(R.id.btn_ok);

        // Setting onClick event listener for the "OK" button
        mBtnOk.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                // Creating an instance of Student class with user input data
                Student student = new Student(mEtSName.getText().toString(),
                Integer.parseInt(mEtSAge.getText().toString()),
                mEtSAddress.getText().toString(),
                mEtSCourse.getText().toString());

                // Creating an intent to open the activity StudentViewActivity
                Intent intent = new Intent(getBaseContext(), StudentViewActivity.class);

                // Passing data as a parecelable object to StudentViewActivity
                intent.putExtra("student",student);

                // Opening the activity
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


13. Update the file AndroidManifest.xml to include the new activity “StudentViewActivity”

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.parcelobjectdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.parcelobjectdemo.MainActivity"
            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="in.wptrafficanalyzer.parcelobjectdemo.StudentViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
</manifest>


14. Screenshots of the application

Inputing Student data

Figure 6 : Inputing Student data

Showing user input data from Pparcelable object

Figure 7 : Showing user input data from Parcelable object


15. Download the source code


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , ,

10 Responses to Android Parcelable Example – Passing data between activities

  1. Daniel Toledo on July 21, 2013 at 8:22 am

    Crack!!!

    • sandeep on December 30, 2014 at 6:41 pm

      Hi George, If we have a student image too in our Parcelable class then how we will read it..

  2. lucky on December 4, 2013 at 5:47 pm

    great post…thanks man

  3. Givita A/P Rama Roa on September 2, 2014 at 9:10 pm

    How to make this data to be appear as notification?

  4. Givita A/P Rama Roa on September 2, 2014 at 10:41 pm

    Hi, How to display the data at notification?

  5. anusha pavan kumar on November 12, 2014 at 11:16 am

    hello sir,
    your tutorial is very nice, very useful. I am an android developer. I will develop and place in Google store, I got a doubt, can u pls help me to resolve it.
    I want code to pass the item id of list view from one activity to other. By using that id i will write the code in the second activity.
    can u pls help me.
    If this works its very useful to me

  6. kangear on December 31, 2014 at 12:51 pm

    Cool, I’m very clear about Parcelable.

  7. Joshi on November 9, 2015 at 12:00 pm

    Hello Sir,

    pls can share me the code of listview with image and text ,when clicking on image of list view item it should be displayed in next activity.

  8. Kushal Gandhi on February 16, 2016 at 12:36 pm

    Thank you sir for this nice tutorial…

  9. Christopher Goguen on March 20, 2016 at 10:15 am

    Thank you, this helped me a ton!

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner