Android: Sending Object from one Activity to another using Parcelable

8 August 2012 By Nithya Vasudevan 16,159 views 6 Comments
19 Flares Twitter 1 Facebook 9 Google+ 9 19 Flares ×

Project Description

  • In the previous Android example here, we created multiple activities and passed data between activities using Bundle and Intent.
  • In this Android tutorial, we will create an example to send complex object from one activity to another. This example creates two activities (SendObjFromActivity and ReceiveObjActivity) each doing the following functions,
    • SendObjFromActivity โ€“ This is the main activity which is presented to the user when launching the application for the first time. It displays a button with onClick listener. When the button is clicked, it creates a Laptop object with properties such as String, double and an Android Bitmap object and sends this object to next activity. It creates and adds a Parcelable object to the intent using putExtra(). Uses main.xml as layout file.
    • ReceiveObjActivityโ€“ It receives the Parcelable object from Intent and display it by setting the value of view elements. Uses display_obj.xml as layout file to display the result.

Environment Used

Setting up development environment

To run this example, you need to setup the development environment with at least one Android platform in your SDK environment. To install Android SDK and configure ADT plugin for Eclipse read this page.

Prerequisites

Android Project

Create an Android project and name it as “SendObjFromActivity“.

strings.xml

Open res/values/string.xml and replace it with following content.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, SendObjFromActivity!</string>
    <string name="activity1_name">SendObjFromActivity</string>
    <string name="activity2_name">ReceiveObjActivity</string>
	<string name="button">Send Obj to another Activity</string>
    <string name="image">Image</string>
</resources>

XML layout files

This application uses two layout files,

res/layout/main.xmlRepresents first screen used by SendObjFromActivity.java
res/layout/display_obj.xmlRepresents second screen used by ReceiveObjActivity.java

Create a new xml file in res/layout and name it as main.xml and copy the following content.
main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

     <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button" />
</LinearLayout>

Create a new xml file in res/layout and name it as display_obj.xml and copy the following content.
display_obj.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:contentDescription="@string/image"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />

    <TextView
        android:id="@+id/desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/icon"
        android:paddingBottom="10dp"
        android:textColor="#CC0033"
        android:textSize="16dp" />
</RelativeLayout>

Create Bean class

Laptop.java

package com.theopentutorials.android.beans;
import android.graphics.Bitmap;

public class Laptop {
	private int id;
	private String brand;
	private double price;
	private Bitmap imageBitmap;
	
	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}	
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}	
	public Bitmap getImageBitmap() {
		return imageBitmap;
	}
	public void setImageBitmap(Bitmap imageBitmap) {
		this.imageBitmap = imageBitmap;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
}

ParcelableLaptop.java

package com.theopentutorials.android.beans;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;

public class ParcelableLaptop implements Parcelable {
	private Laptop laptop;

	public Laptop getLaptop() {
		return laptop;
	}

	public ParcelableLaptop(Laptop laptop) {
		super();
		this.laptop = laptop;
	}

	private ParcelableLaptop(Parcel in) {
		laptop = new Laptop();
		laptop.setId(in.readInt());
		laptop.setBrand(in.readString());
		laptop.setPrice(in.readDouble());
		laptop.setImageBitmap((Bitmap) in.readParcelable(Bitmap.class
				.getClassLoader()));
	}

	/*
	 * you can use hashCode() here.
	 */
	@Override
	public int describeContents() {
		return 0;
	}

	/*
	 * Actual object Serialization/flattening happens here. You need to
	 * individually Parcel each property of your object.
	 */
	@Override
	public void writeToParcel(Parcel parcel, int flags) {
		parcel.writeInt(laptop.getId());
		parcel.writeString(laptop.getBrand());
		parcel.writeDouble(laptop.getPrice());
		parcel.writeParcelable(laptop.getImageBitmap(),
				PARCELABLE_WRITE_RETURN_VALUE);
	}

	/*
	 * Parcelable interface must also have a static field called CREATOR,
	 * which is an object implementing the Parcelable.Creator interface.
	 * Used to un-marshal or de-serialize object from Parcel.
	 */
	public static final Parcelable.Creator<ParcelableLaptop> CREATOR = 
			new Parcelable.Creator<ParcelableLaptop>() {
		public ParcelableLaptop createFromParcel(Parcel in) {
			return new ParcelableLaptop(in);
		}

		public ParcelableLaptop[] newArray(int size) {
			return new ParcelableLaptop[size];
		}
	};
}

Activity

In src folder, create a new Class and name it as “SendObjFromActivity” in the package “com.theopentutorials.android” and copy the following code.

SendObjFromActivity.java

package com.theopentutorials.android;

import java.io.InputStream;

import com.theopentutorials.android.beans.Laptop;
import com.theopentutorials.android.beans.ParcelableLaptop;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class SendObjFromActivity extends Activity implements OnClickListener {
	Button button;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
	Laptop laptop = new Laptop();
	laptop.setId(1);
	laptop.setBrand("Dell");
	laptop.setPrice(699.99);
	
	//if image placed inside res/drawable folder
	//InputStream is = getResources().openRawResource(R.drawable.dell_xps13);
	
	//if image placed inside res/raw folder
	InputStream is = getResources().openRawResource(R.raw.dell_xps13);
	Bitmap bitmap = BitmapFactory.decodeStream(is);
	
	laptop.setImageBitmap(bitmap);
	Intent intent = new Intent(getApplicationContext(),
				ReceiveObjActivity.class);
	//Create Parcelable object
	ParcelableLaptop parcelableLaptop = new ParcelableLaptop(laptop);
		
	//Store Parcelable object in Intent
	intent.putExtra("laptop", parcelableLaptop);
	
	//Start next activity
	startActivity(intent);
   }
}

The above Android activity works as follows,

  • Gets the placed image in res/raw/ folder to read an image as a bit stream in order to convert it to a bitmap so that they will not be optimized,
  • creates laptop object by setting its properties,
  • creates Parcelable object passing the laptop object to its constructor,
  • stores this parcelable object in intent and starts the next activity.

In src folder, create another Class and name it as “ReceiveObjActivity” in the same package and copy the following code.

ReceiveObjActivity.java

package com.theopentutorials.android;

import com.theopentutorials.android.beans.Laptop;
import com.theopentutorials.android.beans.ParcelableLaptop;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class ReceiveObjActivity extends Activity {
	TextView descTxt;
	ImageView imageView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.display_obj);

		findViewsById();

		Intent intent = getIntent();

		ParcelableLaptop parcelableLaptop = (ParcelableLaptop) intent
				.getParcelableExtra("laptop");
		Laptop laptop = parcelableLaptop.getLaptop();
		display(laptop);
	}

	private void findViewsById() {
		descTxt = (TextView) findViewById(R.id.desc);
		imageView = (ImageView) findViewById(R.id.icon);
	}

	private void display(Laptop laptop) {
		String desc = laptop.getId() + ": " + laptop.getBrand() + "\n"
				+ laptop.getPrice();
		descTxt.setText(desc);
		imageView.setImageBitmap(laptop.getImageBitmap());
	}
}

AndroidManifest.xml

Define the two activities in AndroidManifest.xml file

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

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/activity1_name" >
        <activity
            android:name=".SendObjFromActivity"
            android:label="@string/activity1_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ReceiveObjActivity"
            android:label="@string/activity2_name" >
        </activity>
    </application>

</manifest>

Output

Run your application

  • First screen
  • Second screen

Project Folder Structure

The complete folder structure of this example is shown below.

Tags: , , , , , , , , , , , , , ,

  • Yuvaraj M

    Hi, I have one ImageView and Button in Class A,the Second class B having one ImageView
    how can I Pass the ImageView as the Bitmap to class B and how to Display in Class B Image View,

    • http://theopentutorials.com Nithya Vasudevan

      Almost that is what this example does. Consider your Class A as Laptop class which has Bitmap object. ReceiveObjActivity receives the object containing Bitmap and displays it in ImageView.

      • Yuvaraj M

        Thank U

  • Abdisa Bencha Jara

    nice tutorial

  • Sachin P

    Best tutorial

  • Sachin P