How can I pass an object of a custom type from one Activity to another using the putExtra()
method of the class Intent?

- 24,639
- 13
- 81
- 91

- 77,236
- 95
- 209
- 278
-
@UMMA - you don't need to keep marking your questions as "Community Wiki". Have a look here: http://meta.stackexchange.com/questions/11740/what-are-community-wiki-posts-on-stack-overflow – David Webb Jan 26 '10 at 13:11
-
1@Paresh: the link you provided is broken. could you plz provide an alternative? – antiplex Jan 25 '12 at 17:23
-
possible duplicate of [How to pass object from one activity to another in Android](http://stackoverflow.com/questions/2736389/how-to-pass-object-from-one-activity-to-another-in-android) – luke May 01 '13 at 16:02
-
Check out this answer. http://stackoverflow.com/questions/8857546/how-can-i-pass-a-list-of-objects-any-object-through-bundle-from-activity-a-t/32404344#32404344 – Heitor Colangelo Sep 18 '15 at 19:42
-
i found a simple & elegant method http://stackoverflow.com/a/37774966/6456129 – Yessy Jun 12 '16 at 14:37
35 Answers
If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).
From the docs, a simple example for how to implement is:
// simple class that just has one member property as an example
public class MyParcelable implements Parcelable {
private int mData;
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
@Override
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).
Once you have your objects implement Parcelable
it's just a matter of putting them into your Intents with putExtra():
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
Then you can pull them back out with getParcelableExtra():
Intent i = getIntent();
MyParcelable myParcelableObject = (MyParcelable) i.getParcelableExtra("name_of_extra");
If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:
i.putExtra("parcelable_extra", (Parcelable) myParcelableObject);
i.putExtra("serializable_extra", (Serializable) myParcelableObject);

- 47,151
- 38
- 123
- 143
-
15How would this be implemented where mData is an object (e.g. JSONObject) and not an int? – Peter Ajtai Nov 02 '11 at 17:04
-
Parcel has other methods for writing data types such as strings. In the case of a JSONObject you could put it back to JSON and write it as a String. If the object is Serializable and you don't have the access to make it Parcelable, maybe you could serialize it and deserialize it when you unparcel the top-level object? I haven't done this before, just a guess. – Rob Lourens Nov 02 '11 at 18:09
-
324Why can't just pass the object without all this? We want to pass an object that is already in memory. – ceklock Jun 04 '12 at 06:57
-
119@tecnotron its beacuse apps are in different processes, and have separate memory address spaces, you cant just send pointer (reference) to memory block in your process and expect it to be available in another process. – marcinj Jun 21 '12 at 12:29
-
13What do i do if i cant make the object's class serializible or Parceable? – Amel Jose Jun 27 '12 at 19:44
-
3
-
-
3
-
this does not work. see https://code.google.com/p/android/issues/detail?can=2&q=&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&groupby=&sort=&id=6822 – likejudo Mar 11 '14 at 20:48
-
13@ceklock the reason behind this is as follows: When the activity goes behind and later killed from the memory, and then when user opens it from the recents menu, it has to create the Activity where it left off. It has to be the same UI. The Object is not in the memory in this case. But the intent is. – tasomaniac Mar 20 '14 at 11:16
-
@ceklock because it almost always insist a static field somewhere - the best way to get leaks in to your app – martyglaubitz Jun 11 '14 at 12:57
-
And you can do the same with Serializable, but it will work much faster. Check this sample project: https://bitbucket.org/afrishman/androidserializationtest – afrish Mar 29 '15 at 19:06
-
2Parcelable field generator: www.parcelabler.com from http://stackoverflow.com/a/26757130/1277350 – LordParsley Jul 23 '15 at 09:28
-
The ploblem with this approach is that you can only have a parcable object with SIMPLE attributes in it (int, char, String). You cannot make a parcable object with other complex objects as its properties... To make it more clear see the line "out.writeInt(mData);" – Pontios Mar 07 '16 at 13:54
-
i'm implementing **Parcelable** but getting error like unable to marshal value. why this error i'm getting? – AMAN SINGH Sep 19 '16 at 12:51
-
1@Pontios You can put other Parcelables into a Parcelable... or anything that supports Java's native serialization. – Jeremy Logan Sep 28 '16 at 03:12
-
@JeremyLogan how would I create its object when the constructor is private? – huskygrad Oct 25 '16 at 09:34
-
Make sure if you have multiple inner class in your pojo then implement Parcelable in all class. – Arpit Patel Nov 19 '16 at 09:46
-
-
If you pass an object from Activity1 to Activity2, then modify the object in Activity2, your changes will not be shown in Activity1. This is because you are passing a copy of the object's data, not a reference to the object itself. – AtomicBoolean Apr 03 '18 at 16:14
-
I am using Parcelable, but for Map
I am getting an error. How to used it in Parcelable – Shyamaly Lakhadive Apr 17 '21 at 04:16
You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.
In that case you just put the string return value from (new Gson()).toJson(myObject);
and retrieve the string value and use fromJson
to turn it back into your object.
If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.

- 799
- 1
- 13
- 25

- 128,221
- 31
- 203
- 222
-
19I'm guessing because fiXedd's answer solves the same problem without the use of external libraries, in a way that is simply so much preferable, that nobody should ever have a reason to go by the solution i provided (unaware, at the time, of fiXedd's brilliant solution) – David Hedlund Apr 13 '10 at 21:30
-
5I think that is correct. Furthermore, JSON is a protocol more appropriate for client/server and not thread-to-thread. – mobibob Aug 16 '10 at 16:50
-
18Not necessarily a bad idea, esp. since Gson is much simpler to use than to implement parcelable for all the objects you want to send. – uvesten Apr 13 '11 at 15:26
-
7
-
5for convenience sake in many apps, the GSON approach wins if performance is not a priority. Its quicker to code, probably already in use elsewhere in your app, and easier to understand. Code maintainability increases. So u get a +1 for your CW answer. – Richard Le Mesurier Feb 22 '14 at 15:04
-
20Nice answer, although complete solution would be `String s = (new Gson().toJson(client));` and then `Cli client = new Gson().fromJson(s, Cli.class);` – Joaquin Iurchuk Jan 02 '15 at 19:15
-
5+1 to this solution. I completely forgot that I had already been using Gson for use with Retrofit, and this makes things ***a million times easier*** than implementing `Parcelable` for every single object. Gson is absolutely worth using if you do *anything* with web APIs/libraries like Retrofit, because it's literally 2 lines of code to put or get `Intent` extras. I'll add (@mobibob) that JSON is just a data interchange format, and converting objects to JSON strings to send between threads (as `Intent.putExtra()` does already) is, in my opinion, more or less the same as client/server. – Chris Cirefice Jun 23 '15 at 23:34
-
For detailed explaination, see http://learnzone.info/android-passing-object-activity-fragment/ – Madhav Bhattarai Mar 25 '17 at 07:17
You can send serializable object through intent
// send where details is object
ClassName details = new ClassName();
Intent i = new Intent(context, EditActivity.class);
i.putExtra("Editing", details);
startActivity(i);
//receive
ClassName model = (ClassName) getIntent().getSerializableExtra("Editing");
And
Class ClassName implements Serializable {
}

- 18,174
- 13
- 67
- 90

- 2,228
- 10
- 48
- 79
-
2
-
6"Serializable is comically slow on Android. Borderline useless in many cases in fact." look at http://stackoverflow.com/questions/5550670/benefit-of-using-parcelable-instead-of-serializing-object – Seraphim's Nov 19 '13 at 09:37
-
what if the activity is already running, is there need to do startActivity(i); ? I mean, can I make *activity A* call *activity B*, and that returns data to *activity A* ? am I confused ? – Francisco Corrales Morales May 09 '14 at 04:05
-
5@Seraphim's Performance matters if you're serializing a lot of objects, but the user won't notice if serializing one object takes 1 ms or 10 ms. If an intent extra is already `Serializable` but not `Parcelable`, it's seldom worth the hassle to make it `Parcelable`. – Kevin Krumwiede Jul 01 '15 at 03:09
For situations where you know you will be passing data within an application, use "globals" (like static Classes)
Here is what Dianne Hackborn (hackbod - a Google Android Software Engineer) had to say on the matter:
For situations where you know the activities are running in the same process, you can just share data through globals. For example, you could have a global
HashMap<String, WeakReference<MyInterpreterState>>
and when you make a new MyInterpreterState come up with a unique name for it and put it in the hash map; to send that state to another activity, simply put the unique name into the hash map and when the second activity is started it can retrieve the MyInterpreterState from the hash map with the name it receives.

- 9,848
- 3
- 55
- 69

- 56,972
- 13
- 121
- 140
-
26yeah I found it strange that we get given these Intents to use, and then a top engineer tells us to just use globals for our data. But there it is straight from the horses mouth. – Richard Le Mesurier Feb 22 '14 at 15:06
-
1
-
1@uLYsseus think that's the idea, once you're done with them in the activities... so when the relevant activities are destroyed, it'll allow it to gc – Peter Ajtai Nov 25 '14 at 21:39
-
1@RichardLeMesurier I was thinking the same thing, but then I looked into the above referenced Google Groups post from Dianne Hackborn, and she mentions that really the only issue with globals would be when using implicit intents (which can launch an activity outside of your package). This makes sense, as Dianne mentions, because those activities would most likely have zero knowledge of the custom types you are passing to them. Once I read that, it made it clearer to me why globals might not be such a bad route under the circumstances, and I figured I would share in case others were curious too – BMB Mar 18 '16 at 19:55
-
the intents were overengineered to a point where the intent could be passed to a different computer. which is obviously not a good way to do anything when you actually have just one process you're mucking about in. reasons why it's not good: memory use, cpu use, battery use. the last one especially made the design choices with intents quite perplexing in hindsight. there are people who insist that they're a good idea, usually because "google said so". – Lassi Kinnunen Mar 01 '18 at 12:10
Your class should implements Serializable or Parcelable.
public class MY_CLASS implements Serializable
Once done you can send an object on putExtra
intent.putExtra("KEY", MY_CLASS_instance);
startActivity(intent);
To get extras you only have to do
Intent intent = getIntent();
MY_CLASS class = (MY_CLASS) intent.getExtras().getSerializable("KEY");
If your class implements Parcelable use next
MY_CLASS class = (MY_CLASS) intent.getExtras().getParcelable("KEY");
I hope it helps :D

- 2,285
- 28
- 22
-
8Your class must implement `Serializable` is wrong. The class can implement `Parcelable` for example. – Marc Plano-Lesay Oct 02 '13 at 13:41
-
what are the difference between Parcelable and Serializable @Kernald ? in terms of processing time is it more slower / not best practice or something? – gumuruh Jul 17 '14 at 07:47
-
While `Serializable` is a standard Java interface, `Parcelable` is Android-specific. In terms of performance, Parcelable is more efficient: http://www.developerphil.com/parcelable-vs-serializable/ – Marc Plano-Lesay Jul 17 '14 at 08:08
implement serializable in your class
public class Place implements Serializable{
private int id;
private String name;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then you can pass this object in intent
Intent intent = new Intent(this, SecondAct.class);
intent.putExtra("PLACE", Place);
startActivity(intent);
int the second activity you can get data like this
Place place= (Place) getIntent().getSerializableExtra("PLACE");
But when the data become large,this method will be slow.

- 685
- 2
- 8
- 35

- 2,758
- 1
- 31
- 38
Short answer for fast need
1. Implement your Class to Serializable.
If you have any inner Classes don't forget to implement them to Serializable too!!
public class SportsData implements Serializable
public class Sport implements Serializable
List<Sport> clickedObj;
2. Put your object into Intent
Intent intent = new Intent(SportsAct.this, SportSubAct.class);
intent.putExtra("sport", clickedObj);
startActivity(intent);
3. And receive your object in the other Activity Class
Intent intent = getIntent();
Sport cust = (Sport) intent.getSerializableExtra("sport");

- 6,405
- 5
- 39
- 42
-
see this link, https://stackoverflow.com/questions/2139134/how-to-send-an-object-from-one-android-activity-to-another-using-intents – RejoylinLokeshwaran Sep 01 '17 at 07:31
-
You can achieve the same thing by implementing Parcelable interface. 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. – Kwnstantinos Nikoloutsos Jul 04 '18 at 00:41
if your object class implements Serializable
, you don't need to do anything else, you can pass a serializable object.
that's what i use.

- 735
- 2
- 10
- 19
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 that can hold common data can be named 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.
Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html
B. Shared Preferences
Suppose you want to store username. So there will be now two things a Key Username, Value Value.
How to store
// Create an 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
editor.commit();
Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.
How to fetch
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");
http://developer.android.com/reference/android/content/SharedPreferences.html
C. Object Serialization
Object serialization is used if we want to save an object state to send it over the 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();
variableStorage.setInString(inString);
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 a tutorial for this to refer this link
http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html
D. CommonUtilities
You can make a class by your self which can contain common data which you frequently need in your project.
Sample
public class CommonUtilities {
public static String className = "CommonUtilities";
}
E. Passing Data through Intents
Please refer to this tutorial for this option of passing data.

- 1,286
- 13
- 27

- 26,128
- 21
- 90
- 126
You can use android BUNDLE to do this.
Create a Bundle from your class like:
public Bundle toBundle() {
Bundle b = new Bundle();
b.putString("SomeKey", "SomeValue");
return b;
}
Then pass this bundle with INTENT. Now you can recreate your class object by passing bundle like
public CustomClass(Context _context, Bundle b) {
context = _context;
classMember = b.getString("SomeKey");
}
Declare this in your Custom class and use.
-
2Preferable to direct Parcelable implementation, IMHO. Bundle implements Parcelable by itself so you still have the performance gain while avoiding all the trouble implementing it yourself. Instead, you can use key-value pairs to store and retrieve the data which is more robust by far than relying on mere order. – Risadinha May 06 '13 at 13:42
-
Parcelable seems complicated to me, in my above answer I am using toBundle method from class on it's object so object is converted to bundle and then we can use constructor to convert bundle to class object. – om252345 May 08 '13 at 09:32
-
This solution is only viable if you are passing a single object through an intent. – TheIT Aug 07 '14 at 22:36
-
-
-
Is it addresses issue, because i guess they said how to pass object not string – blackHawk May 28 '17 at 10:07
Thanks for parcelable help but i found one more optional solution
public class getsetclass implements Serializable {
private int dt = 10;
//pass any object, drwabale
public int getDt() {
return dt;
}
public void setDt(int dt) {
this.dt = dt;
}
}
In Activity One
getsetclass d = new getsetclass ();
d.setDt(50);
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("hashmapkey", d);
Intent inew = new Intent(SgParceLableSampelActivity.this,
ActivityNext.class);
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
inew.putExtras(b);
startActivity(inew);
Get Data In Activity 2
try { setContentView(R.layout.main);
Bundle bn = new Bundle();
bn = getIntent().getExtras();
HashMap<String, Object> getobj = new HashMap<String, Object>();
getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
getsetclass d = (getsetclass) getobj.get("hashmapkey");
} catch (Exception e) {
Log.e("Err", e.getMessage());
}

- 6,077
- 11
- 38
- 58

- 5,015
- 1
- 28
- 56
-
1good answer, but increase your Coding Standards... +1 though for bringing Serializable in the competition however Parcellables are a lot faster... – Amit May 29 '12 at 06:00
I use Gson with its so powerful and simple api to send objects between activities,
Example
// This is the object to be sent, can be any object
public class AndroidPacket {
public String CustomerName;
//constructor
public AndroidPacket(String cName){
CustomerName = cName;
}
// other fields ....
// You can add those functions as LiveTemplate !
public String toJson() {
Gson gson = new Gson();
return gson.toJson(this);
}
public static AndroidPacket fromJson(String json) {
Gson gson = new Gson();
return gson.fromJson(json, AndroidPacket.class);
}
}
2 functions you add them to the objects that you want to send
Usage
Send Object From A to B
// Convert the object to string using Gson
AndroidPacket androidPacket = new AndroidPacket("Ahmad");
String objAsJson = androidPacket.toJson();
Intent intent = new Intent(A.this, B.class);
intent.putExtra("my_obj", objAsJson);
startActivity(intent);
Receive In B
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
String objAsJson = bundle.getString("my_obj");
AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);
// Here you can use your Object
Log.d("Gson", androidPacket.CustomerName);
}
I use it almost in every project i do and I have no performance issues.

- 727
- 7
- 12

- 16,271
- 19
- 99
- 149
I struggled with the same problem. I solved it by using a static class, storing any data I want in a HashMap. On top I use an extension of the standard Activity class where I have overriden the methods onCreate an onDestroy to do the data transport and data clearing hidden. Some ridiculous settings have to be changed e.g. orientation-handling.
Annotation: Not providing general objects to be passed to another Activity is pain in the ass. It's like shooting oneself in the knee and hoping to win a 100 metres. "Parcable" is not a sufficient substitute. It makes me laugh... I don't want to implement this interface to my technology-free API, as less I want to introduce a new Layer... How could it be, that we are in mobile programming so far away from modern paradigm...

- 767
- 7
- 12
In your first Activity:
intent.putExtra("myTag", yourObject);
And in your second one:
myCustomObject myObject = (myCustomObject) getIntent().getSerializableExtra("myTag");
Don't forget to make your custom object Serializable:
public class myCustomObject implements Serializable {
...
}

- 4,304
- 4
- 34
- 44
-
Parcelable is better than Serializable! Avoid to use Serializable in your Android code! – Filipe Brito Jul 06 '15 at 20:49
Another way to do this is to use the Application
object (android.app.Application). You define this in you AndroidManifest.xml
file as:
<application
android:name=".MyApplication"
...
You can then call this from any activity and save the object to the Application
class.
In the FirstActivity:
MyObject myObject = new MyObject();
MyApplication app = (MyApplication) getApplication();
app.setMyObject(myObject);
In the SecondActivity, do :
MyApplication app = (MyApplication) getApplication();
MyObject retrievedObject = app.getMyObject(myObject);
This is handy if you have objects that have application level scope i.e. they have to be used throughout the application. The Parcelable
method is still better if you want explicit control over the object scope or if the scope is limited.
This avoid the use of Intents
altogether, though. I don't know if they suits you. Another way I used this is to have int
identifiers of objects send through intents and retrieve objects that I have in Maps in the Application
object.

- 13,172
- 10
- 68
- 94
-
1It is not the right way to do things since the objects may be variable ,yours may work if you talk about static object along the life cycle of the app , but some times we need passiing objects that may generated using webservice or so http://stackoverflow.com/a/2736612/716865 – Muhannad A.Alhariri May 01 '13 at 12:38
-
I've used it successfully with objects generated from webservices by having an application scope `Map` where the objects are stored and retrieved by using an identifier. The only real problem with this approach is that Android clears memory after a while so you have to check for nulls on your onResume (I think that Objects passed in intents are persisted but am not sure). Apart from that I don't see this as being significantly inferior. – Saad Farooq May 02 '13 at 02:38
-
This is the best answer. It shows how different activities can reference the same data model. It took me far to long to discover this! – Markus Feb 11 '16 at 08:16
in your class model (Object) implement Serializable, for Example:
public class MensajesProveedor implements Serializable {
private int idProveedor;
public MensajesProveedor() {
}
public int getIdProveedor() {
return idProveedor;
}
public void setIdProveedor(int idProveedor) {
this.idProveedor = idProveedor;
}
}
and your first Activity
MensajeProveedor mp = new MensajeProveedor();
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("mensajes",mp);
startActivity(i);
and your second Activity (NewActivity)
MensajesProveedor mensajes = (MensajesProveedor)getIntent().getExtras().getSerializable("mensajes");
good luck!!

- 3,652
- 6
- 41
- 61
public class SharedBooking implements Parcelable{
public int account_id;
public Double betrag;
public Double betrag_effected;
public int taxType;
public int tax;
public String postingText;
public SharedBooking() {
account_id = 0;
betrag = 0.0;
betrag_effected = 0.0;
taxType = 0;
tax = 0;
postingText = "";
}
public SharedBooking(Parcel in) {
account_id = in.readInt();
betrag = in.readDouble();
betrag_effected = in.readDouble();
taxType = in.readInt();
tax = in.readInt();
postingText = in.readString();
}
public int getAccount_id() {
return account_id;
}
public void setAccount_id(int account_id) {
this.account_id = account_id;
}
public Double getBetrag() {
return betrag;
}
public void setBetrag(Double betrag) {
this.betrag = betrag;
}
public Double getBetrag_effected() {
return betrag_effected;
}
public void setBetrag_effected(Double betrag_effected) {
this.betrag_effected = betrag_effected;
}
public int getTaxType() {
return taxType;
}
public void setTaxType(int taxType) {
this.taxType = taxType;
}
public int getTax() {
return tax;
}
public void setTax(int tax) {
this.tax = tax;
}
public String getPostingText() {
return postingText;
}
public void setPostingText(String postingText) {
this.postingText = postingText;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(account_id);
dest.writeDouble(betrag);
dest.writeDouble(betrag_effected);
dest.writeInt(taxType);
dest.writeInt(tax);
dest.writeString(postingText);
}
public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>()
{
public SharedBooking createFromParcel(Parcel in)
{
return new SharedBooking(in);
}
public SharedBooking[] newArray(int size)
{
return new SharedBooking[size];
}
};
}
Passing the data:
Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();
i.putParcelableArrayListExtra("data", (ArrayList<? extends Parcelable>) dataList);
intent.putExtras(bundle);
startActivity(intent);
Retrieving the data:
Bundle bundle = getIntent().getExtras();
dataList2 = getIntent().getExtras().getParcelableArrayList("data");

- 4,328
- 6
- 52
- 58
the most easiest solution i found is.. to create a class with static data members with getters setters.
set from one activity and get from another activity that object.
activity A
mytestclass.staticfunctionSet("","",""..etc.);
activity b
mytestclass obj= mytestclass.staticfunctionGet();

- 39,067
- 29
- 104
- 160

- 77,236
- 95
- 209
- 278
-
This is not generic enough to support an arbitrary class. What are you going to do if the custom object has a file reference in it? Do you want to pass the name or process the content? Parcelable will give one such options via the flag settings. – mobibob Aug 16 '10 at 16:52
-
1or creata serializable class to pass to another activity whatever you want to pass. – UMAR-MOBITSOLUTIONS May 09 '11 at 13:03
-
10Just remember not to put big fat objects. The lifetime of that object will be the same as the lifetime of the application. And never ever store views. This method also guarantees memory leaks. – Reno Sep 17 '11 at 19:07
-
1This answer is useful but not a better solution in terms of memory and resource optimization – Atul Bhardwaj Jul 13 '12 at 06:11
-
this answer does not make sense to me - a static function can only access static members - how will you pass non static members? – likejudo Mar 30 '14 at 00:38
-
1This breaks OOP principles by introducing global variables. You never know, in which state they are, whether they are set or no, they are used by many threads and you have to deal with this complexity. It is usually a good memory leak, because you don't even know, when to free these variables. Not to say that it introduces hard direct coupling between different modules of the application. – afrish Jul 27 '14 at 13:00
-
2
-
@IcyFlame basically the OP answered their own question and accepted it even though other answers are way superior. wtf. – Varun Oct 13 '16 at 00:23
-
GSON, parcelable and serializable are better answers than this really. – Leontsev Anton Oct 26 '17 at 13:00
Using google's Gson library you can pass object to another activities.Actually we will convert object in the form of json string and after passing to other activity we will again re-convert to object like this
Consider a bean class like this
public class Example {
private int id;
private String name;
public Example(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
We need to pass object of Example class
Example exampleObject=new Example(1,"hello");
String jsonString = new Gson().toJson(exampleObject);
Intent nextIntent=new Intent(this,NextActivity.class);
nextIntent.putExtra("example",jsonString );
startActivity(nextIntent);
For reading we need to do the reverse operation in NextActivity
Example defObject=new Example(-1,null);
//default value to return when example is not available
String defValue= new Gson().toJson(defObject);
String jsonString=getIntent().getExtras().getString("example",defValue);
//passed example object
Example exampleObject=new Gson().fromJson(jsonString,Example .class);
Add this dependancy in gradle
compile 'com.google.code.gson:gson:2.6.2'

- 3,377
- 3
- 22
- 37
Create Android Application
File >> New >> Android Application
Enter Project name: android-pass-object-to-activity
Pakcage: com.hmkcode.android
Keep other defualt selections, go Next till you reach Finish
Before start creating the App we need to create POJO class “Person” which we will use to send object from one activity to another. Notice that the class is implementing Serializable interface.
Person.java
package com.hmkcode.android;
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
// getters & setters....
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Two Layouts for Two Activities
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"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name" />
<EditText
android:id="@+id/etName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tvAge"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Age" />
<EditText
android:id="@+id/etAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</LinearLayout>
<Button
android:id="@+id/btnPassObject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Pass Object to Another Activity" />
</LinearLayout>
activity_another.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"
android:orientation="vertical"
>
<TextView
android:id="@+id/tvPerson"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="center"
android:gravity="center_horizontal"
/>
</LinearLayout>
Two Activity Classes
1)ActivityMain.java
package com.hmkcode.android;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
Button btnPassObject;
EditText etName, etAge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPassObject = (Button) findViewById(R.id.btnPassObject);
etName = (EditText) findViewById(R.id.etName);
etAge = (EditText) findViewById(R.id.etAge);
btnPassObject.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// 1. create an intent pass class name or intnet action name
Intent intent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");
// 2. create person object
Person person = new Person();
person.setName(etName.getText().toString());
person.setAge(Integer.parseInt(etAge.getText().toString()));
// 3. put person in intent data
intent.putExtra("person", person);
// 4. start the activity
startActivity(intent);
}
}
2)AnotherActivity.java
package com.hmkcode.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class AnotherActivity extends Activity {
TextView tvPerson;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
// 1. get passed intent
Intent intent = getIntent();
// 2. get person object from intent
Person person = (Person) intent.getSerializableExtra("person");
// 3. get reference to person textView
tvPerson = (TextView) findViewById(R.id.tvPerson);
// 4. display name & age on textView
tvPerson.setText(person.toString());
}
}

- 1,141
- 9
- 22
I know this is late but it is very simple.All you have do is let your class implement Serializable like
public class MyClass implements Serializable{
}
then you can pass to an intent like
Intent intent=......
MyClass obje=new MyClass();
intent.putExtra("someStringHere",obje);
To get it you simpley call
MyClass objec=(MyClass)intent.getExtra("theString");

- 1,414
- 1
- 10
- 17
Easiest and java way of doing is : implement serializable in your pojo/model class
Recommended for Android for performance view: make model parcelable

- 1,226
- 1
- 10
- 14
you can use putExtra(Serializable..) and getSerializableExtra() methods to pass and retrieve objects of your class type; you will have to mark your class Serializable and make sure that all your member variables are serializable too...

- 98
- 1
- 8
Intent i = new Intent();
i.putExtra("name_of_extra", myParcelableObject);
startACtivity(i);

- 169
- 1
- 9
If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.
In Activity 1:
Intent intent = new Intent(getApplicationContext(), Activity2.class);
service.setSavedOrder(order);
startActivity(intent);
In Activity 2:
private Service service;
private Order order;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quality);
service = Service.getInstance();
order = service.getSavedOrder();
service.setSavedOrder(null) //If you don't want to save it for the entire session of the app.
}
In Service:
private static Service instance;
private Service()
{
//Constructor content
}
public static Service getInstance()
{
if(instance == null)
{
instance = new Service();
}
return instance;
}
private Order savedOrder;
public Order getSavedOrder()
{
return savedOrder;
}
public void setSavedOrder(Order order)
{
this.savedOrder = order;
}
This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.

- 351
- 2
- 18
-
What are the downsides of this approach? It seems so logical and slim. I always read you should not do that but I never get a good explanation about what could go wrong. – Markus Feb 11 '16 at 07:13
-
Since I can't edit my comment anymore: Isn't this the only possible solution to get a reference to an object instead of a copy? I need to retrieve the same obejct and not a copy! – Markus Feb 11 '16 at 07:21
-
I think this is somewhat discouraged because of the high coupling it leads to. But yes, as far as I can see, this approach is the most viable if you need the actual object. As always in programming, you can do whatever you want, you just want to do it carefully. This solution worked for me, and I prefer it since I use that architecture anyway. – Kitalda Feb 24 '16 at 09:21
-
Actually I ended up extending the Application class and stored my datamodel there. In the Intents I only relayed the ID of the data objects which could be used to retrieve the original object from the Application class. Also the extended application class notifies all objects that use the datamodel if it changes via a standard listener concept. I know that this fits only my case where I need to share a datamodel over the whole application but for that case its perfect and no static classes and fields needed also! – Markus Feb 24 '16 at 13:10
By far the easiest way IMHO to parcel objects. You just add an annotation tag above the object you wish to make parcelable.
An example from the library is below https://github.com/johncarl81/parceler
@Parcel
public class Example {
String name;
int age;
public Example(){ /*Required empty bean constructor*/ }
public Example(int age, String name) {
this.age = age;
this.name = name;
}
public String getName() { return name; }
public int getAge() { return age; }
}

- 1,815
- 1
- 18
- 22
First implement Parcelable in your class. Then pass object like this.
SendActivity.java
ObjectA obj = new ObjectA();
// Set values etc.
Intent i = new Intent(this, MyActivity.class);
i.putExtra("com.package.ObjectA", obj);
startActivity(i);
ReceiveActivity.java
Bundle b = getIntent().getExtras();
ObjectA obj = b.getParcelable("com.package.ObjectA");
The package string isn't necessary, just the string needs to be the same in both Activities

- 179,855
- 19
- 132
- 245

- 7,212
- 5
- 56
- 67
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "xyz@gmail.com");
startActivity(intent);
Retrieve on another activity (YourActivity)
String s = getIntent().getStringExtra("USER_NAME");
This is ok for simple kind 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;
getters...
setters...
}
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);
startActivity(intent);
Bundle bundle = getIntent().getExtras();
String empStr = bundle.getString("EMP");
Gson gson = new Gson();
Type type = new TypeToken<Employee>() {
}.getType();
Employee selectedEmp = gson.fromJson(empStr, type);

- 732,580
- 175
- 1,330
- 1,459

- 997
- 1
- 8
- 9
In Koltin
Add kotlin extension in your build.gradle.
apply plugin: 'kotlin-android-extensions'
android {
androidExtensions {
experimental = true
}
}
Then create your data class like this.
@Parcelize
data class Sample(val id: Int, val name: String) : Parcelable
Pass Object with Intent
val sample = Sample(1,"naveen")
val intent = Intent(context, YourActivity::class.java)
intent.putExtra("id", sample)
startActivity(intent)
Get object with intent
val sample = intent.getParcelableExtra("id")

- 350
- 2
- 12
If you are not very particular about using the putExtra feature and just want to launch another activity with objects, you can check out the GNLauncher (https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher) library I wrote in an attempt to make this process more straight forward.
GNLauncher makes sending objects/data to an Activity from another Activity etc as easy as calling a function in the Activity with the required data as parameters. It introduces type safety and removes all the hassles of having to serialize, attaching to the intent using string keys and undoing the same at the other end.

- 33
- 1
- 5
POJO class "Post" (Note that it is implemented Serializable)
package com.example.booklib;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;
public class Post implements Serializable{
public String message;
public String bitmap;
List<Comment> commentList = new ArrayList<Comment>();
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getBitmap() {
return bitmap;
}
public void setBitmap(String bitmap) {
this.bitmap = bitmap;
}
public List<Comment> getCommentList() {
return commentList;
}
public void setCommentList(List<Comment> commentList) {
this.commentList = commentList;
}
}
POJO class "Comment"(Since being a member of Post class,it is also needed to implement the Serializable)
package com.example.booklib;
import java.io.Serializable;
public class Comment implements Serializable{
public String message;
public String fromName;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
}
}
Then in your activity class, you can do as following to pass the object to another activity.
ListView listview = (ListView) findViewById(R.id.post_list);
listview.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Post item = (Post)parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this,CommentsActivity.class);
intent.putExtra("post",item);
startActivity(intent);
}
});
In your recipient class "CommentsActivity" you can get the data as the following
Post post =(Post)getIntent().getSerializableExtra("post");

- 8,335
- 5
- 52
- 76
The simplest would be to just use the following where the item is a string:
intent.putextra("selected_item",item)
For receiving:
String name = data.getStringExtra("selected_item");
-
3its for string , integer and etc only but i want the object and using static object its only possible. – UMAR-MOBITSOLUTIONS Jun 25 '10 at 05:28
Start another activity from this activity pass parameters via Bundle Object
Intent intent = new Intent(this, YourActivity.class);
Intent.putExtra(AppConstants.EXTRAS.MODEL, cModel);
startActivity(intent);
Retrieve on another activity (YourActivity)
ContentResultData cModel = getIntent().getParcelableExtra(AppConstants.EXTRAS.MODEL);

- 640
- 4
- 14
We can send data one Activty1 to Activity2 with multiple ways like.
1- Intent
2- bundle
3- create an object and send through intent
.................................................
1 - Using intent
Pass the data through intent
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
intentActivity1.putExtra("name", "Android");
startActivity(intentActivity1);
Get the data in Activity2 calss
Intent intent = getIntent();
if(intent.hasExtra("name")){
String userName = getIntent().getStringExtra("name");
}
..................................................
2- Using Bundle
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
Bundle bundle = new Bundle();
bundle.putExtra("name", "Android");
intentActivity1.putExtra(bundle);
startActivity(bundle);
Get the data in Activity2 calss
Intent intent = getIntent();
if(intent.hasExtra("name")){
String userName = getIntent().getStringExtra("name");
}
..................................................
3- Put your Object into Intent
Intent intentActivity1 = new Intent(Activity1.this, Activity2.class);
intentActivity1.putExtra("myobject", myObject);
startActivity(intentActivity1);
Receive object in the Activity2 Class
Intent intent = getIntent();
Myobject obj = (Myobject) intent.getSerializableExtra("myobject");

- 1,088
- 8
- 17
I know it's a little bit late, but if you want to do this for a few objects only why don't you just declare you objects as a public static objects in your destination activity ?
public static myObject = new myObject();
and from your source activity just give it a value ?
destinationActivity.myObject = this.myObject;
in your source activity you can use it like any global object. Fro a large number of object it may cause some memory issues but for a few number of objects i think this is the best way to do

- 41
- 10
-
2Making static any object will mark it as an active object. JVM and DVM will skip cleaning that resource at the time of finalizing (Mark and weep algorithm). So you need to null that object manually for memory management. IN SHORT NOT A GOOD APPROACH – Gaganpreet Singh Jan 15 '15 at 06:07
-
1i have clearly said this approach may cause some memory issues .... but for one or two objects you can manually put it to null, not a big deal ! – Mothana Jan 15 '15 at 08:03
-
You can use if you are fine with this limitation of creating a static object. – Gaganpreet Singh Jan 15 '15 at 08:44