By kaibuki

2010-04-29 10:06:52 8 Comments

I am trying to work on sending an object of my customer class from one Activity and display it in another Activity.

The code for the customer class:

public class Customer {

    private String firstName, lastName, Address;
    int Age;

    public Customer(String fname, String lname, int age, String address) {

        firstName = fname;
        lastName = lname;
        Age = age;
        Address = address;

    public String printValues() {

        String data = null;

        data = "First Name :" + firstName + " Last Name :" + lastName
        + " Age : " + Age + " Address : " + Address;

        return data;

I want to send its object from one Activity to another and then display the data on the other Activity.

How can I achieve that?


@khalid 2013-10-31 07:08:21

Use gson to convert your object to JSON and pass it through intent. In the new Activity convert the JSON to an object.

In your build.gradle, add this to your dependencies

implementation ''

In your Activity, convert the object to json-string:

Gson gson = new Gson();
String myJson = gson.toJson(vp);
intent.putExtra("myjson", myjson);

In your receiving Activity, convert the json-string back to the original object:

Gson gson = new Gson();
YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class);

For Kotlin it's quite the same

Pass the data

val gson = Gson()
val intent = Intent(this,
intent.putExtra("identifier", gson.toJson(your_object))

Receive the data

val gson = Gson()
val yourObject = gson.fromJson<YourObject>(intent.getStringExtra("identifier"),

@James Roeiter 2013-12-22 18:30:44

Its an overkill , gson is just a type of string serialization to json , its better to implement Serializable or Paracable .

@sagits 2015-01-22 14:03:23

Theres no need to implement serializable in every object and in every project (waste of time) if you can use a library (gson) that handles that. And about overkill, theres dual and quadcore phones out there, they can handle even a list following this answer idea.

@nurgasemetey 2015-02-09 11:02:05

I would also recommend using gson because gson can also serialize arraylists in addition to above.

@Chad Bingham 2016-04-16 20:42:50

This is great! In my case, I am using a library that the objects do no implement serializable or parcelable. So this is my only option afaik

@jose920405 2016-09-16 15:32:48

@ojonugwa ochalifu 2017-08-09 12:11:54

This is the "best" option. Some classes are so simple, you don't need to over complicate their implementation by implementing serializable

@Jossef Harush 2018-05-18 10:35:18

IMHO, thinking developer experience, I go with this solution. I don't mind paying the minor cost of converting my simple pojo to json while keeping the representing class as simple as possible.

@john ktejik 2018-10-08 18:33:01

Isn't gson slower than serialize?

@Randy 2019-05-22 18:30:58

The Kotlin method is getString, not getStringExtra, but it won't let me edit the answer because edits have to be at least 6 characters

@Steven Mark Ford 2013-11-18 19:36:07

In my experience there are three main solutions, each with their disadvantages and advantages:

  1. Implementing Parcelable

  2. Implementing Serializable

  3. Using a light-weight event bus library of some sort (for example, Greenrobot's EventBus or Square's Otto)

Parcelable - fast and Android standard, but it has lots of boilerplate code and requires hard-coded strings for reference when pulling values out the intent (non-strongly typed).

Serializable - close to zero boilerplate, but it is the slowest approach and also requires hard-coded strings when pulling values out the intent (non-strongly typed).

Event Bus - zero boilerplate, fastest approach, and does not require hard-coded strings, but it does require an additional dependency (although usually lightweight, ~40 KB)

I posted a very detailed comparison around these three approaches, including efficiency benchmarks.

@OlivierH 2017-04-01 14:16:05

Link to the article is dead. Still available on webarchive :…

@Mauker 2017-06-28 19:04:14

It's a shame that the link is down :(

@JuliuszJ 2018-02-06 10:03:33

The problem of usage of Event Bus is when target Activity is recreated due to rotation for example. In this case target Activity has not access to passed object because this object was consumed from the bus by earlier call.

@Steven Mark Ford 2018-02-09 00:01:40

@JuliuszJ how does this differ to the other options? you always going to have to persist some sort of state in the target activity when it initially receives it no matter what approach. There is also the concept of a sticky bus message if you need.

@Steven Mark Ford 2018-06-11 23:40:02

I have taken the link to my blog away for now. Until I decide to re-instate my blog.

@ByWaleed 2019-04-16 10:36:59

Parcelable is the fastest and with this generator (, you can paste your class and it can generate the code for you. Simple.

@Yo Apps 2019-06-19 15:48:23

@ByWaleed ... I absolutely agree, I always use this site, makes stuff without any hassels. However, I have had a lot of unsuccessful tries, when I try to use a POJO that is composed of another Object. For some reason its out put doesnt really work.

@ByWaleed 2019-07-02 10:10:14

@Yo Apps, I think you might be missing some small details which means it doesn't work. Look into the errors that you get and that can lead to where the issue is. Never the less, you cannot guarantee 100% compatibility with automated system like this and will have to use your programming intellect to find errors. Often, they are small but can also be due to not fully understand what you want to achieve or how to use the available tools to achieve that outcome.

@Mayur Chudasama 2014-01-21 10:14:21

Create your own class Customer as following:

import import;
public class Customer implements Serializable
    private String name;
    private String city;

    public Customer()

    public Customer(String name, String city)
    { name;;
    public String getName() 
        return name;
    public void setName(String name) 
    { = name;
    public String getCity() 
        return city;
    public void setCity(String city) 
    { city;


In your onCreate() method

protected void onCreate(Bundle savedInstanceState) 

    Customer cust=new Customer();

    Intent intent=new Intent(abc.this,xyz.class);

In xyz activity class you need to use the following code:

Intent intent=getIntent();
Customer cust=(Customer)intent.getSerializableExtra("bundle");

@AK Joshi 2014-11-21 06:18:11

..Check your code you are passing "bundle" as key for put cust obj & getting from "class" ..pls use one key either "class" or "bundle" ..

@Arul Mani 2019-03-29 09:52:59

I face Error: Parcelable encountered IOException writing serializable object

@Samuh 2010-04-29 10:39:05

One option could be letting your custom class implement the Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.


//To pass:
intent.putExtra("MyClass", obj);

// To retrieve object in second Activity

Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:

class MainClass implements Serializable {

    public MainClass() {}

    public static class ChildClass implements Serializable {

        public ChildClass() {}

@Pentium10 2010-05-27 13:40:57

I have a same situation, after I implement Serializable, do I have to do anything special in my class, do I have to implement some methods?

@Samuh 2011-05-09 21:09:25

@OD: In my defense, I never said this was the best option; OP just asked for alternatives and I suggested one. Thanks anyways.

@Nate 2011-08-21 23:48:43

Why is Serializable not a good option? It's a well-known interface, there's a good chance that peoples' classes may already implement it (ArrayList, for example, is already Serializable). Why should you have to change your data objects to add extra code simply to pass them from one class to another? That seems like a bad design. I can imagine there may be some performance impact at some level, but I'd think that in 99% of cases, people are passing small amounts of data, and they won't care. Simpler and portable is sometimes better, too.

@Nate 2011-08-21 23:50:12

I'll also add that as this question is not a general one, but a specific one (regarding the poster's Customer class), in this case performance should be insignificant with such a simple, tiny data object.

@Sander Versluys 2011-09-13 09:56:22

Quite the contrary, Parcelable is not advised as mechanism to pass object between activities, it's ment for IPC. So serializable is a good option, just use it sensibly...

@Slauma 2011-10-02 16:26:23

@Sander: Is this answer (…) wrong then? He says that Parcelable IS specifically designed for that purpose (and much faster than Serializable). I am a confused.

@Sander Versluys 2011-10-03 16:28:58

@Slauma well as a matter of fact both do work, but Parcelable was initially created for use in IPC because the overhead when using Serializable. But for simple object transfer between activities it's not noticable and all the plumping involved using Parcelables ain't worth it IMO. They would not include the putSerializable method in the Bundles interface when the use of it is discouraged and to date it is not deprecated. So in my opinion, when your sure you don't need IPC use the Serializable interface, it's much easier. Avoid large object graphs, but same would be true van a Parcelable.

@Steven Elliott 2012-06-25 01:53:35

I would just like to add a real world example .. I was using serializable to pass a complex object between activities. Creating the intent was taking 200ms, and reading it in the receiving activity took 100+ms, after changing to parcelable it dropped to 6ms and 68ms respectively. So it's definitely worth using parcelable for speed

@BlackHatSamurai 2012-08-14 02:41:43

Parcelable might be good for speed, but it is complicated to implement. What if you have 8 objects you need to pass between activities, are you going to make each one Parcelable? It would make more sense to use Serializable instead. When you implement Parcelable you have to add a lot of code to the class, and order fields in a very specific manner; Serializable you don't. Ultimately, I think it comes down to how many objects you are passing and what you are trying to do.

@Gaurav Arora 2012-12-06 07:41:25

Serializable is a standard Java interface. You simply mark a class Serializable by implenting the interface, and Java will automatically serialize it in certain situations. Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme

@none 2014-03-04 14:45:28

if you are wondering why not Serializable: "The problem with this approach is that reflection is used and it is a slow process. This mechanism also tends to create a lot of temporary objects and cause quite a bit of garbage collection." from

@Steven Mark Ford 2014-07-24 23:29:12

Serializable is too slow for large POJOs. Using a Bus is a much better pattern.

@Zapnologica 2014-10-07 16:41:54

Why cant one just pass an object as is? Whats the point of serializing and then de-serializing in the other activity? Its not like you are parsing it between different languages or machines? Its From one class to another?

@gilsaints88 2015-01-28 15:34:07

I think the accepted answer here is sufficient and more recommended in terms of performance compared to Serializable or Parcelable. In Android, encapsulation is not really important and encapsulation is really not advised in Android because of performance reasons. Just remember the gotchas of using static value that can lead to something unexpected depending on your use case.

@JamEngulfer 2016-04-29 18:03:47

So how come we can pass a String, which is technically an object, but not any other object type? iOS handles this functionality through a single variable assignment, why does Android have this prohibiting method of passing data?

@Markus 2018-12-03 09:47:01

How do I access the get methods in the passed object from:- getIntent().getSerializableExtra("MyClass");

@Beast77 2019-02-13 14:06:25

@Markus, you simply use the getters and the setters that you have declared in the model class. To add to this whole Serializabe v Parceleable argument, I would like to make a note about retrofit. If you want to pass objects that you get from an API using retrofit, both of those interfaces have the same speed. Your app's efficiency is constant

@Krishnabhadra 2019-09-04 05:07:14

Upvoted since this answer tells about a method recommended by Android. But If serializable (or parcelable) is the recommended solution, then it is like going back to write code in the 1970s. The OOPS concept is created around objects. If a list and detail screen cannot share the same object, then we may as well write code in caves. Terrible from Android

@SohailAziz 2012-04-16 18:50:11

  • Using global static variables is not good software engineering practice.
  • Converting an object's fields into primitive data types can be a hectic job.
  • Using serializable is OK, but it's not performance-efficient on the Android platform.
  • Parcelable is specifically designed for Android and you should use it. Here is a simple example: Passing custom objects between Android activities

You can generate Parcelable code for you class using this site.

@Dr. aNdRO 2014-03-27 13:26:24

What if my object contains nested Arraylist?

@VH-NZZ 2014-05-13 10:43:52

Well perhaps but one should really take ``performance'' with a grain of salt imo. If that comes at the price of implementing Parcelable then I'd rather keep my POJO classes Android-agnostic and use Serializable.

@Steven Mark Ford 2014-07-24 23:27:46

I don't agree that you should use Parcelable. A simple BUS pattern is much more efficient at runtime and saves a heck of a lot of dev time.

@nucleo 2015-03-29 18:54:46

According to this benchmark Serializable is much faster than Parcelable. Please stop sharing this 5 year old nonsense about Parcelable.

@Justin 2016-02-18 21:48:17

As it stands, this answer is almost link-only. Can you add some example code or something into this answer itself?

@breakline 2016-02-26 08:05:11

How are global static variables "not good software engineering practice"? You can make something like a singleton cache and/or data grid then pass around ID's or similar. When you pass around references in Java you're using global static variables in a sense anyway as they point to the same object.

@Cristian Hoyos 2016-08-23 14:29:38

Use Parcelable is the good choice definitely.

@guru_007 2017-07-31 18:47:41

but , when implementing Parcelable interface ,and receiving through Receiver am getting RuntimeException .

@Ayaz Alifov 2015-02-23 20:55:20

This question is also discussed in another Stack Overflow question. Please have a look at a solution to Passing data through intent using Serializable. The main point is about using Bundle object which stores the necessary data inside Intent.

 Bundle bundle = new Bundle();

 bundle.putSerializable(key1, value1);
 bundle.putSerializable(key2, value2);
 bundle.putSerializable(key3, value3);


To extract values:

 Bundle bundle = new Bundle();

 for (String key : bundle.keySet()) {
 value = bundle.getSerializable(key));

Advantage of Serializable is its simplicity. However, you should consider using Parcelable method if you need many data to be transferred, because Parcelable is specifically designed for Android and it is more efficient than Serializable. You can create Parcelable class using:

  1. an online tool - parcelabler
  2. a plugin for Android Studio - Android Parcelable code generator

@DroidNinja 2017-06-23 12:06:01

Start another activity from this activity and pass parameters via Bundle Object

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");

Retrive data on another activity (YourActivity)

String s = getIntent().getStringExtra("USER_NAME");

This is ok for simple kind of data type. But if u want to pass complex data in between activity. U need to serialize it first.

Here we have Employee Model

class Employee{
    private String empId;
    private int age;
    print Double salary;


You can use Gson lib provided by google to serialize the complex data like this

String strEmp = new Gson().toJson(emp);
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("EMP", strEmp);

Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
            Gson gson = new Gson();
            Type type = new TypeToken<Employee>() {
            Employee selectedEmp = gson.fromJson(empStr, type);

@Ragavendra M 2018-02-26 09:18:56

TypeToken<> is deprecated. Whats the alternate?

@Bhuvaneshwaran Vellingiri 2017-05-29 13:17:21

Pass one activity to another:

startActivity(new Intent(getBaseContext(),GetActivity.class).putExtra("passingkey","passingvalue"));

Get values:

String myvalue= getIntent().getExtras("passingkey");

@dara 2017-03-14 16:42:07

Above answers almost all correct but for those who doesn't undestand those answers Android has powerfull class Intent with help of it you share data between not only activity but another components of Android (broadcasr receiver, servises for content provide we use ContetnResolver class no Intent). In your activity you build intent

Intent intent = new Intent(context,SomeActivity.class);

In your receving activity you have

public class SomeActivity extends AppCompactActivity {

    public void onCreate(...){
          SomeObject someObject = getIntent().getExtras().getParceable("key");


You have to implement Parceable or Serializable interface on your object in order to share between activities. It is hard to implement Parcealbe rather than Serializable interface on object that's why android has plugin especially for this.Download it and use it

@Yessy 2016-06-12 13:46:58

I found a simple & elegant method:

  • NO Parcelable
  • NO Serializable
  • NO Static Field
  • No Event Bus

Method 1

Code for the first activity:

    final Object objSent = new Object();
    final Bundle bundle = new Bundle();
    bundle.putBinder("object_value", new ObjectWrapperForBinder(objSent));
    startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));        
    Log.d(TAG, "original object=" + objSent);

Code for the second activity:

    final Object objReceived = ((ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value")).getData();
    Log.d(TAG, "received object=" + objReceived);

you will find objSent & objReceived have the same hashCode, so they are identical.

But why can we pass a java object in this way?

Actually, android binder will create global JNI reference for java object and release this global JNI reference when there are no reference for this java object. binder will save this global JNI reference in the Binder object.

*CAUTION: this method ONLY work unless the two activities run in the same process, otherwise throw ClassCastException at (ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value") *

class ObjectWrapperForBinder defination

public class ObjectWrapperForBinder extends Binder {

    private final Object mData;

    public ObjectWrapperForBinder(Object data) {
        mData = data;

    public Object getData() {
        return mData;

Method 2

  • for the sender,
    1. use custom native method to add your java object to JNI global reference table(via JNIEnv::NewGlobalRef)
    2. put the return integer (actually, JNIEnv::NewGlobalRef return jobject, which is a pointer, we can cast it to int safely) to your Intent(via Intent::putExtra)
  • for the receiver
    1. get integer from Intent(via Intent::getInt)
    2. use custom native method to restore your java object from JNI global reference table (via JNIEnv::NewLocalRef)
    3. remove item from JNI global reference table(via JNIEnv::DeleteGlobalRef),

But Method 2 has a little but serious issue, if the receiver fail to restore the java object (for example, some exception happen before restore the java object, or the receiver Activity does not exist at all), then the java object will become an orphan or memory leak, Method 1 don't have this issue, because android binder will handle this exception

Method 3

To invoke the java object remotely, we will create a data contract/interface to describe the java object, we will use the aidl file


package com.example.objectwrapper;
interface IDataContract {
    int func1(String arg1);
    int func2(String arg1);

Code for the first activity

    final IDataContract objSent = new IDataContract.Stub() {

        public int func2(String arg1) throws RemoteException {
            // TODO Auto-generated method stub
            Log.d(TAG, "func2:: arg1=" + arg1);
            return 102;

        public int func1(String arg1) throws RemoteException {
            // TODO Auto-generated method stub
            Log.d(TAG, "func1:: arg1=" + arg1);
            return 101;
    final Bundle bundle = new Bundle();
    bundle.putBinder("object_value", objSent.asBinder());
    startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));
    Log.d(TAG, "original object=" + objSent);

Code for the second activity:

change the android:process attribute in AndroidManifest.xml to a non-empty process name to make sure the second activity run in another process

    final IDataContract objReceived = IDataContract.Stub.asInterface(getIntent().getExtras().getBinder("object_value"));
    try {
        Log.d(TAG, "received object=" + objReceived + ", func1()=" + objReceived.func1("test1") + ", func2()=" + objReceived.func2("test2"));
    } catch (RemoteException e) {
        // TODO Auto-generated catch block

In this way, we can pass an interface between two activities even though they run in different process, and call the interface method remotely

Method 4

method 3 seem not simple enough because we must implement an aidl interface. If you just want to do simple task and the method return value is unnecessary, we can use android.os.Messenger

Code for the first activity( sender):

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    public static final int MSG_OP1 = 1;
    public static final int MSG_OP2 = 2;

    public static final String EXTRA_MESSENGER = "messenger";

    private final Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.e(TAG, "handleMessage:: msg=" + msg);
            switch (msg.what) {
            case MSG_OP1:

            case MSG_OP2:



    protected void onCreate(Bundle savedInstanceState) {

        startActivity(new Intent(this, SecondActivity.class).putExtra(EXTRA_MESSENGER, new Messenger(mHandler)));

Code for the second activity ( receiver ):

public class SecondActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {

        final Messenger messenger = getIntent().getParcelableExtra(MainActivity.EXTRA_MESSENGER);
        try {
            messenger.send(Message.obtain(null, MainActivity.MSG_OP1, 101, 1001, "10001"));
            messenger.send(Message.obtain(null, MainActivity.MSG_OP2, 102, 1002, "10002"));
        } catch (RemoteException e) {
            // TODO Auto-generated catch block


All the Messenger.send will execute in a Handler asynchronously and sequentially.

Actually, android.os.Messenger is also an aidl interface, if you have the android source code, you can find a file named IMessenger.aidl

package android.os;

import android.os.Message;

/** @hide */
oneway interface IMessenger {
    void send(in Message msg);

@SkidRunner 2016-07-13 19:57:37

Sorry I did not see that you had binding in your answer as well I feel that your answer is also very elegant.

@karan 2019-04-17 10:32:24

Wow.... This man's 1st method is tremendous..... When you have very big/larger sized objects that works well

@SkidRunner 2016-07-13 19:03:21

Hello all I see a lot of good options but I was wondering why Binding hasn't been used?

Passing a reference to an object just seems more efficient to me than serializing and desterilizing objects, but I have not done a deep dive to see if that is what is going on behind the scenes.

Creating a Binder is simple enough...

public class MyBinder extends Binder {

    private Object myObject;

    public MyBinder(Object object) {
        myObject = object;

    public Object getObject() {
        return myObject;


And creating the parcelable to use it isn't that bad ether.

public class MyParcelable implements Parcelable {

    private Object myObject;

    public MyParcelable() {

    public MyParcelable(Parcel parcel) {
        myObject = ((MyBinder)parcel.readStrongBinder()).getObject();

    public void setObject(Object object) {
        myObject = object;

    public Object getObject() {
        return myObject;

    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeStrongBinder(new MyBinder(myObject));

    public int describeContents() {
        return myObject == null ? 0 : 1;

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

        public MyParcelable createFromParcel(Parcel parcel) {
            return new MyParcelable(parcel);

        public MyParcelable[] newArray(int length) {
            return new MyParcelable[length];


This logic is really cool because you are actually passing a reference from activity to activity.

I would advise checking for nulls and if the instanceof Binder is MyBinder!

and to implement this you just...

Send it off

Object myObject = "some object";
MyParcelable myParcelable = new MyParcelable();

intent.putExtra("MyParcelable", myParcelable);

Get it back

myParcelable = (MyParcelable) getIntent().getExtras().getParcelable("MyParcelable");
myObject = myParcelable.getObject();

Heck someone could get all crazy and make this sucker a true generic.

@Ads 2011-08-03 08:42:32

While calling an activity

Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj);

In receive the activity by

Customer customerObjInToClass = getIntent().getExtras().getParcelable("myCustomerObj");

Please make sure that customer class implements parcelable

public class Customer implements Parcelable {

    private String firstName, lastName, address;
    int age;

    /* all your getter and setter methods */

    public Customer(Parcel in ) {
        readFromParcel( in );

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public LeadData createFromParcel(Parcel in ) {
            return new Customer( in );

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

    public void writeToParcel(Parcel dest, int flags) {


    private void readFromParcel(Parcel in ) {

        firstName = in .readString();
        lastName  = in .readString();
        address   = in .readString();
        age       = in .readInt();

@newman 2011-09-10 21:28:45

Adhavan, I got a question. When you create the first Intent class, you pass in fromClass.this as the first argument. Is there a way to retrieve this object in the receiving activity class?

@Ads 2011-09-12 08:23:05

Miliu, fromClass fr = (fromClass) getParent(); is this what u needed?

@newman 2011-09-25 03:08:40

Adhava, I actually did this, but fr is null. Any idea why?

@Ads 2011-09-26 08:06:36

miliu,please share your exception trace by that we can look into it.

@Steven Mark Ford 2014-07-24 23:30:43

Parcelable has a heck of a lot of unecessary boiler plate code and is quite frankly a waste of time. Rather use a Bus. See my post below.

@Q07 2015-03-03 10:24:17

Create two methods in your custom Class like this

public class Qabir {

    private int age;
    private String name;


    Qabir(int age,String name){

    // method for sending object
    public String toJSON(){
        return "{age:" + age + ",name:\"" +name +"\"}";

    // method for get back original object
    public void initilizeWithJSONString(String jsonString){

        JSONObject json;        
        try {
            json =new JSONObject(jsonString );
        } catch (JSONException e) {

Now in your sender Activity do like this

Qabir q= new Qabir(22,"KQ");    
Intent in=new Intent(this,SubActivity.class);
in.putExtra("obj", q.toJSON());
startActivity( in);

And in your receiver Activity

Qabir q =new Qabir();

@user4715375 2015-11-18 06:38:35

We can pass the object from one activity to another activity:

SupplierDetails poSuppliersDetails = new SupplierDetails();

Inside poSuppliersDetails we have some values. Now I am sending this object to target activity:

Intent iPODetails = new Intent(ActivityOne.this, ActivityTwo.class);
iPODetails.putExtra("poSuppliersDetails", poSuppliersDetails);

How to get this in ACtivityTwo:

private SupplierDetails supplierDetails;
    supplierDetails =(SupplierDetails) getIntent().getSerializableExtra("poSuppliersDetails");

@user3289522 2014-02-09 12:14:17

Crete a class like bean class and implement the Serializable interface. Then we can pass it through the intent method, for example:

intent.putExtra("class", BeanClass);

Then get it from the other activity, for example:

BeanClass cb = intent.getSerializableExtra("class");

@Bebin T.N 2013-08-10 19:03:10

I am using parcelable to send data from one activity to another acivity. Here is my code that works fine in my project.

public class Channel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String uniqueID;
    private String name;
    private String logo;
    private String thumb;

     * @return The cid
    public String getCid() {
        return cid;

     * @param cid
     *     The cid to set
    public void setCid(String cid) {
        this.cid = cid;

     * @return The uniqueID
    public String getUniqueID() {
        return uniqueID;

     * @param uniqueID
     *     The uniqueID to set
    public void setUniqueID(String uniqueID) {
        this.uniqueID = uniqueID;

     * @return The name
    public String getName() {
        return name;

     * @param name
     *            The name to set
    public void setName(String name) { = name;

     * @return the logo
    public String getLogo() {
        return logo;

     * @param logo
     *     The logo to set
    public void setLogo(String logo) {
        this.logo = logo;

     * @return the thumb
    public String getThumb() {
        return thumb;

     * @param thumb
     *     The thumb to set
    public void setThumb(String thumb) {
        this.thumb = thumb;

    public Channel(Parcel in) {

    public static final Parcelable.Creator<Channel> CREATOR = new Parcelable.Creator<Channel>() {
        public Channel createFromParcel(Parcel in) {
            return new Channel(in);

        public Channel[] newArray(int size) {

            return new Channel[size];

    public void readFromParcel(Parcel in) {
        String[] result = new String[5];

        this.cid = result[0];
        this.uniqueID = result[1]; = result[2];
        this.logo = result[3];
        this.thumb = result[4];

    public int describeContents() {
        return 0;

    public void writeToParcel(Parcel dest, int flags) {

        dest.writeStringArray(new String[] { this.cid, this.uniqueID,
      , this.logo, this.thumb});

In activityA use it like this:

Bundle bundle = new Bundle();
bundle.putParcelableArrayList("channel",(ArrayList<Channel>) channels);
Intent intent = new Intent(ActivityA.this,ActivityB.class);

In ActivityB use it like this to get data:

Bundle getBundle = this.getIntent().getExtras();
List<Channel> channelsList = getBundle.getParcelableArrayList("channel");

@Nikhil Agrawal 2013-05-19 20:00:10

There are a couple of ways by which you can access variables or objects in other classes or Activity.

A. Database

B. Shared preferences.

C. Object serialization.

D. A class which can hold common data can be named as Common Utilities. It depends on you.

E. Passing data through Intents and Parcelable Interface.

It depends upon your project needs.

A. Database

SQLite is an open source database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.


B. Shared preferences

Suppose you want to store username. So there will now be two things, a key username, value value.

How to store

 // Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);

 //Now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();

 //Put your value
 editor.putString("userName", "stackoverlow");

 //Commits your edits

Using putString(), putBoolean(), putInt(), putFloat(), and putLong() you can save your desired dtatype.

How to fetch

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

C. Object serialization

Object serlization is used if we want to save an object state to send it over a network or you can use it for your purpose also.

Use Java beans and store in it as one of his fields and use getters and setter for that.

JavaBeans are Java classes that have properties. Think of properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

public class VariableStorage implements Serializable  {

    private String inString;

    public String getInString() {
        return inString;

    public void setInString(String inString) {
        this.inString = inString;

Set the variable in your mail method by using

VariableStorage variableStorage = new VariableStorage();

Then use object serialzation to serialize this object and in your other class deserialize this object.

In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized. That is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

If you want tutorial for this refer to:

D. CommonUtilities

You can make a class by yourself which can contain common data which you frequently need in your project.


public class CommonUtilities {

    public static String className = "CommonUtilities";


E. Passing data through intents

Please refer the tutorial Android – Parcel data to pass between Activities using Parcelable classes for this option of passing data.

@Anton Duzenko 2013-05-03 18:10:42

  1. I know that static is bad, but it seems that we're forced to use it here. The problem with parceables/seriazables is that the two activities have duplicate instances of the same object = waste of memory and CPU.

    public class IntentMailBox {
        static Queue<Object> content = new LinkedList<Object>();

Calling activity

Intent intent = new Intent(LevelsActivity.this, LevelActivity.class);

Called activity (note that onCreate() and onResume() may be called multiple times when the system destroys and recreates activities)

if (IntentMailBox.content.size()>0)
    level = (Level) IntentMailBox.content.poll();
    // Here you reload what you have saved in onPause()
  1. Another way is to declare a static field of the class that you want to pass in that very class. It will serve only for this purpose. Don't forget that it can be null in onCreate, because your app package has been unloaded from memory by system and reloaded later.

  2. Bearing in mind that you still need to handle activity lifecycle, you may want to write all the data straight to shared preferences, painful with complex data structures as it is.

@Dhiral Pandya 2012-01-25 20:30:59

public class MyClass implements Serializable{
    Here is your instance variable

Now you want to pass the object of this class in startActivity. Simply use this:

Bundle b = new Bundle();
b.putSerializable("name", myClassObject);

This works here because MyClass implements Serializable.

@Amitsharma 2016-09-30 07:05:09

can you please explain or elaborate more

@Amitsharma 2016-09-30 07:07:08

HomeworkData homeworkData = homeWorksList.get(position); Intent intent = new Intent(c, HomeWorkActivitydetail.class); Bundle b = new Bundle(); b.putSerializable("CompleteData", homeworkData); intent.putExtras(b); c.startActivity(intent); at a time of object add gives me some error for adding object elements can we not pass complete object with this

@Amitsharma 2016-09-30 07:08:06

inside of homeworkData i am having some values these are come to add

@Mustafa Güven 2011-10-19 20:19:07

Implement your class with Serializable. Let's suppose that this is your entity class:


@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
public class Deneme implements Serializable {

    public Deneme(double id, String name) { = id; = name;

    public double getId() {
        return id;

    public void setId(double id) { = id;

    public String getName() {

    public void setName(String name) { = name;

    private double id;
    private String name;

We are sending the object called dene from X activity to Y activity. Somewhere in X activity;

Deneme dene = new Deneme(4,"Mustafa");
Intent i = new Intent(this, Y.class);
i.putExtra("sampleObject", dene);

In Y activity we are getting the object.

Intent i = getIntent();
Deneme dene = (Deneme)i.getSerializableExtra("sampleObject");

That's it.

@JibW 2012-02-21 15:39:43

It was really helpfull for me. Thanks... But when receiving the passed object, the syntax Should be [ Deneme dene = (Deneme)i.getSerializableExtra("sampleObject"); ] ... Is it ???

@Shajeel Afzal 2013-06-17 19:06:35

@MustafaGüven But i am getting classCastException: java.lang.Long by doing so. Can you please explain why?

@Mustafa Güven 2013-06-18 13:18:43

There is no any relation with my answer. It's very different thing you are getting. Could you share your codes?

@Steven Mark Ford 2014-07-24 23:35:30

Serializable is too slow for large POJOs. Using a Bus is a much better pattern.

@Alston 2014-09-24 09:53:15

Why should I have to prefix (Serializable) to the object?

@Mustafa Güven 2014-09-24 11:00:21

simple. it's because of transmission. you have to look for the detailed explanation of serialization and its purpose in java (same in c#)

@gilsaints88 2015-01-28 15:36:00

Just a side note, AFAIK in Android it's really not recommended to encapsulate class members with setters and getters because of a little bit of performance overhead. It's more advised to access them directly.

@CommonSenseCode 2015-10-29 13:45:53

prefer this implementation parceable is so annoying to use and difference is not noticeable for small objects

@Varis 2011-10-07 05:55:30

You can try to use that class. The limitation is that it can't be used outside of one process.

One activity:

 final Object obj1 = new Object();
 final Intent in = new Intent();
 in.putExtra(EXTRA_TEST, new Sharable(obj1));

Other activity:

final Sharable s = in.getExtras().getParcelable(EXTRA_TEST);
final Object obj2 = s.obj();

public final class Sharable implements Parcelable {

    private Object mObject;

    public static final Parcelable.Creator < Sharable > CREATOR = new Parcelable.Creator < Sharable > () {
        public Sharable createFromParcel(Parcel in ) {
            return new Sharable( in );

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

    public Sharable(final Object obj) {
        mObject = obj;

    public Sharable(Parcel in ) {
        readFromParcel( in );

    Object obj() {
        return mObject;

    public int describeContents() {
        return 0;

    public void writeToParcel(final Parcel out, int flags) {
        final long val = SystemClock.elapsedRealtime();
        put(val, mObject);

    private void readFromParcel(final Parcel in ) {
        final long val = in .readLong();
        mObject = get(val);


    private static final HashMap < Long, Object > sSharableMap = new HashMap < Long, Object > (3);

    synchronized private static void put(long key, final Object obj) {
        sSharableMap.put(key, obj);

    synchronized private static Object get(long key) {
        return sSharableMap.remove(key);

@Dennso 2011-09-17 12:08:19

As mentioned in the comments, this answer breaks encapsulation and tightly couples components, which is very likely not what you want. The best solution is probably making your object Parcelable or Serializable, as other responses explain. Having said that, the solution solves the problem. So if you know what you are doing:

Use a class with static fields:

public class Globals {
    public static Customer customer = new Customer();

Inside the activities you can use:

Activity From:

Globals.customer = myCustomerFromActivity;

Activity Target:

myCustomerTo = Globals.customer;

It's an easy way to pass information for activities.

@Chris McCabe 2014-12-18 11:44:53

I think this is an atrocious answer which totally breaks encapsulation, and tightly couples components. The correct solution is to use parcelable as stated in one of the answers lower down. This is horrible practice!!

@Brian White 2015-01-04 22:09:48

Sometimes encapsulation is important and sometimes things are already tightly coupled so it really makes little difference. Idealism alone is not worth hours of extra coding (plus more maintenance down the road). Just recognize the limitations and possible problems from doing things this away and then decide if more effort up-front to be "proper" is worthwhile in the long run.

@Yaroslav 2015-03-09 21:38:51

That's how it should look like: one statement to put, one statement to get, not dozens of lines of boilerplate error-prone code.

@uesports135 2015-04-25 13:17:28

This can cause issues with using the back button. Using the above example, say you have customerDetails activity. If at any point you allow the switching between customers, then that global value will be overwritten so going back via the back button will not always work as intended.

@El Abogato 2015-05-03 11:59:12

If the user is using Target Activity, then changes to another Application (opening notifications, or selecting an image from gallery app), may be possible that the current activity gets Distroyed. When the user gets back, you will get a null pointer Exception because this value was initialised in the previous activity.

@GriffinTaimer 2015-07-26 14:48:44

There are millions of successful commercial projects which does not follow idealism completely, and +1 to Brian White for putting it in the correct way. When the crunch time approaches I'm pretty sure a shorter development time is preferred than a tiny degradation in performance.

@infinite-loop 2015-07-30 21:30:55

This is a hack. Sometimes we have to hack code, but not when there are other better ways of doing it.

@Chris Woolfe 2018-04-03 15:40:28

@Umesh 2010-04-29 12:09:16

The best way is to have a class (call it Control) in your application that will hold a static variable of type 'Customer' (in your case). Initialize the variable in your Activity A.

For example:

Control.Customer = CustomerClass;

Then go to Activity B and fetch it from Control class. Don't forget to assign a null after using the variable, otherwise memory will be wasted.

@user166390 2013-01-15 03:22:22

@aez Because it's sloppy from a design viewpoint and will break horribly if the Intent is ever in another process.

@Ryan R 2013-01-18 17:39:53

You will run into issues when resuming your app to Activity B. Since the Activity can be killed by Android and the object will not be saved.

@MJB 2010-04-29 11:27:25

You could also write the object's data into temporary Strings and ints, and pass them to the activity. Of course that way, you get the data transported, but not the object itself.

But if you just want to display them, and not use the object in another method or something like that, it should be enough. I did it the same way to just display data from one object in another activity.

String fName_temp   = yourObject.getFname();
String lName_temp   = yourObject.getLname();
String age_temp     = yourObject.getAge();
String address_temp = yourObject.getAddress();

Intent i = new Intent(this, ToClass.class);
i.putExtra("fname", fName_temp);
i.putExtra("lname", lName_temp);
i.putExtra("age", age_temp);
i.putExtra("address", address_temp);


You could also pass them in directly instead of the temp ivars, but this way it's clearer, in my opinion. Additionally, you can set the temp ivars to null so that they get cleaned by the GarbageCollector sooner.

Good luck!

On a side note: override toString() instead of writing your own print method.

As mentioned in the comments below, this is how you get your data back in another activity:

String fName = getIntent().getExtras().getInt("fname");

@Alister 2010-10-30 05:17:00

get your data back again with: String fName = getIntent().getExtras().getInt("fname");

@Eric Leschinski 2012-01-01 01:00:08

To get the data back: Bundle extras = getIntent().getExtras(); String val = extras.getString("fname");

@Steven Mark Ford 2014-07-24 23:31:53

This can quickly become infeasible for large POJOs. Rather use a Bus. See my post below.

@MJB 2014-07-31 11:54:37

as I mentioned in my answer, this is for simple usecases where you don't need the object itself, but rather just some values of it. It's not ment to be a soslution for complex usecases.

@Muhammad Saqib 2015-08-26 09:33:27

Good idea to pass a single object, but I'm trying to pass an array of unknown size of my object. Perhaps your solution is not for passing object arrays.

@MJB 2015-08-26 15:00:49

yeah the original question asked to pass one object to another activity, not an array. there are more efficient and better solutions for that.

@Vidar Vestnes 2010-04-29 11:18:15

If you choose use the way Samuh describes, remember that only primitive values can be sent. That is, values that are parcable. So, if your object contains complex objects these will not follow. For example, variables like Bitmap, HashMap etc... These are tricky to pass by the intent.

In general I would advice you to send only primitive datatypes as extras, like String, int, boolean etc. In your case it would be: String fname, String lname, int age, and String address.

My opinion: More complex objects are better shared by implementing a ContentProvider, SDCard, etc. It's also possible to use a static variable, but this may fastly lead to error-prone code...

But again, it's just my subjective opinion.

@kimkevin 2015-10-04 11:44:57

I used to set object with Pacelable or Serializable to transfer, but whenever I add other variables to object(model), I have to register it all. It's so nconvenient.

It's super easy to transfer object between activities or fragments.

Android DataCache

@Jayesh Kalkani 2015-07-13 05:48:30

Pass object from one activity to another activity.

(1) source activity

Intent ii = new Intent(examreport_select.this,

                    (Serializable) your List<ArraList<String>> object here);

(2) destination acitivity

List<ArrayList<String>> aa = (List<ArrayList<String>>) getIntent()

@jinais 2014-11-02 06:32:06

I had always wondered why this can't be as simple as calling into a method of the other activity. I recently wrote a utility library that makes it almost as simple as that. You can check it out here(

GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in tha Activity with the required data as parameters. It introduces type safety and removes all the hastles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.


Define an interface with the methods you want to call on the Activity to launch.

public interface IPayload {
    public void sayHello(String name, int age);

Implement the above interface on the Activity to launch into. Also notify GNLauncher when the activity is ready.

public class Activity_1 extends Activity implements IPayload {

    protected void onCreate(Bundle savedInstanceState) {
        //Notify GNLauncher when the Activity is ready. 

    public void sayHello(String name, int age) {
        Log.d("gnlib_test", "Hello " + name + "! \nYour age is: " + age);

In the other Activity, get a proxy to the above Activity and call any method with the desired parameters.

public class Activity_2 extends Activity {
    public void onClick(View v) {
        ((IPayload)GNLauncher.get().getProxy(this, IPayload.class, Activity_1.class)).sayHello(name, age);

The first activity will be launched and the method called into with the required parameters.


Please refer to for information on how to add the dependencies.

@TimJowers2 2014-09-05 19:54:15

Android Activity objects can be destroyed and reconstituted. So, you will need to use another approach to look them - or any object they create!!! - up. That is, you could pass as static class reference but then the object handle (Java calls these "references", as does SmallTalk; but they are not references in the sense of C or assembly) will be possibly invalid later because a "feature" of Android OE is any Activity can be annihilated and reconstituted later.

The original question asked "How to pass object from one activity to another in Android" and nobody has answered that. For sure, you can serialized (Serializable, Parcelable, to/from JSON) and pass a copy of the object's data and a new object having the same data could be created; but it will NOT have the same references/handles. Also, many others mentioned you can store the reference in a static store. And that will work unless Android decides to onDestroy your Activity.

So, to really solve the original question you would need a static lookup plus each object will update its reference when/if it is recreated. E.g. each Android Activity would relist itself if its onCreate is called. You can also see how some people use the task list to search out an Activity by name. (system is temporarily destroying this instance of the activity to save space..getRunningTasks, the task list is effectively a specialized listing of the most recent object instance of each Activity).

For reference:

Stopped: "The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere."

onDestroy "system is temporarily destroying this instance of the activity to save space."

So, the Message Bus is a workable solution. It basically "punts". Rather than try to have references to objects; then you re-architect your design to use MessagePassing instead of SequentialCode. Exponentially harder to debug; but it lets you ignore these sort of OperatingEnvironment understandings. Effectively, each object method access is inverted so the caller posts a Message and the object itself defines a handler for that message. Lots more code but can make it robust with the Android OE restrictions.

If all you want is the top Activity (typical thing in Android apps due to "Context" being needed everywhere), then you can just have each Activity lists itself as "top" in the static global space whenever its onResume is called. Then your AlertDialog or whatever which needs a context can just grab it from there. Also, its a bit yucky to use a global but can simplifying passing a Context up and down everywhere and, for sure, when you use a MessageBus then IT IS global anyways.

@TimJowers2 2014-09-08 15:24:41

Otto has pro of being able to run it externally in just a a plain old Java app. So, good for dev and testing without having to mess with Android. Otto has con of big learning curve and most of what it solves is already solved in Android ways (local broadcast etc) or in normal app dev approaches ( you can write a much simpler global lookup than the global lookup of Otto, normal approaches are much more approachable for vectoring/F3 through code and for stepping through debugging).

@Roger Sanoli 2012-06-20 13:20:42

I made a singleton helper class that holds temporary objects.

public class IntentHelper {

    private static IntentHelper _instance;
    private Hashtable<String, Object> _hash;

    private IntentHelper() {
        _hash = new Hashtable<String, Object>();

    private static IntentHelper getInstance() {
        if(_instance==null) {
            _instance = new IntentHelper();
        return _instance;

    public static void addObjectForKey(Object object, String key) {
        getInstance()._hash.put(key, object);

    public static Object getObjectForKey(String key) {
        IntentHelper helper = getInstance();
        Object data = helper._hash.get(key);
        helper = null;
        return data;

Instead of putting your objects within Intent, use IntentHelper:

IntentHelper.addObjectForKey(obj, "key");

Inside your new Activity, you can get the object:

Object obj = (Object) IntentHelper.getObjectForKey("key");

Bear in mind that once loaded, the object is removed to avoid unnecessary references.

@Umair 2012-09-26 05:59:15

Good idea! Additionally may be you can create an additional class ObjectContainer { Object, obj; boolean permanent; ....} Idea is that, you may pass a boolean in add method if you need to keep object persistant and don't remove when we call get. It will help keeping some global objects. Like may be an open bluetooth connection etc.

@Steven Mark Ford 2014-07-24 23:34:43

Cute but don't re-invent the wheel. Bus pattern is elegant and more powerful. See my post below.

@Woppi 2017-12-20 12:32:13

@StevenMarkFord so does Bus pattern still holds true til this day? I am trying to improve a codebase with a code like this accessing data between activities: BookActivity.getInstance().recommendationResponse in RoomsActivity

@Salvador 2018-08-07 13:46:12

When the receiving Activity is recreated (eg on screen rotation) obj becomes null. To avoid this, obj should be stored somewhere to get it again. Indeed the Json solution stores object data in Intent.

Related Questions

Sponsored Content

29 Answered Questions

53 Answered Questions

21 Answered Questions

[SOLVED] How do I create a transparent Activity on Android?

51 Answered Questions

[SOLVED] Stop EditText from gaining focus at Activity startup

21 Answered Questions

[SOLVED] How do I call one constructor from another in Java?

  • 2008-11-12 20:10:19
  • ashokgelal
  • 798305 View
  • 2116 Score
  • 21 Answer
  • Tags:   java constructor

32 Answered Questions

35 Answered Questions

31 Answered Questions

[SOLVED] Activity restart on rotation Android

77 Answered Questions

9 Answered Questions

Sponsored Content