How to pass an object from one activity to another on Android
Solution 1
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.
Actual Code:
In Your Custom Model/Object Class:
public class YourClass implements Serializable {
At other class where using the Custom Model/Class:
//To pass:
intent.putExtra("KEY_NAME", myObject);
myObject is of type "YourClass". Then to retrieve from another activity, use getSerializableExtra get the object using same Key name. And typecast to YourClass is needed:
// To retrieve object in second Activity
myObject = (YourClass) getIntent().getSerializableExtra("KEY_NAME");
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() {}
}
}
Solution 2
Implement your class with Serializable. Let's suppose that this is your entity class:
import java.io.Serializable;
@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
public class Deneme implements Serializable {
public Deneme(double id, String name) {
this.id = id;
this.name = name;
}
public double getId() {
return id;
}
public void setId(double id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.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);
startActivity(i);
In Y activity we are getting the object.
Intent i = getIntent();
Deneme dene = (Deneme)i.getSerializableExtra("sampleObject");
That's it.
Solution 3
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 'com.google.code.gson:gson:2.8.4'
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, YourActivity::class.java)
intent.putExtra("identifier", gson.toJson(your_object))
startActivity(intent)
Receive the data
val gson = Gson()
val yourObject = gson.fromJson<YourObject>(intent.getStringExtra("identifier"), YourObject::class.java)
Solution 4
- 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.
Solution 5
While calling an activity
Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj);
In toClass.java 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];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(firstName);
dest.writeString(lastName);
dest.writeString(address);
dest.writeInt(age);
}
private void readFromParcel(Parcel in ) {
firstName = in .readString();
lastName = in .readString();
address = in .readString();
age = in .readInt();
}
Comments
-
Adil Bhatty almost 2 years
I am trying to work on sending an object of my customer class from one
Activity
and display it in anotherActivity
.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 otherActivity
.How can I achieve that?
-
kimkevin over 8 yearsI used to set object to Pacelable or Serializable, but whenever I add other variables, I have to add it all to functions to get and set for Pacelable or Serializable. so I made DataCache to transfer between activities and fragments. github.com/kimkevin/AndroidDataCache It's super easy to transfer object.
-
Lukas over 3 yearsI've created a wrapper TrackedReference<Any> that is parcelable and serializable without requiring marshaling (serializing or parcelizing) for the underlying type: stackoverflow.com/a/64944753/3405387
-
nhCoder over 3 yearswhy don't you just use static variables and access it from other activity, without recreating it in memory and also sterilization of object may consume resources.
-
-
Pentium10 almost 14 yearsI 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?
-
Alister over 13 yearsget your data back again with: String fName = getIntent().getExtras().getInt("fname");
-
Samuh about 13 years@OD: In my defense, I never said this was the best option; OP just asked for alternatives and I suggested one. Thanks anyways.
-
MLQ over 12 yearsYeah, I think I actually agree with you. Making those objects
static
is the better workaround if it's simply impractical to keep invokingputExtra()
for every property you'd like to pass on. For example, right now, I want to pass anArrayList
that contains objects. I might as well make my ArrayListstatic
instead. -
Nate over 12 yearsWhy 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 over 12 yearsI'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.
-
newman over 12 yearsAdhavan, 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 over 12 yearsMiliu, fromClass fr = (fromClass) getParent(); is this what u needed?
-
Sander Versluys over 12 yearsQuite 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...
-
newman over 12 yearsAdhava, I actually did this, but fr is null. Any idea why?
-
Ads over 12 yearsmiliu,please share your exception trace by that we can look into it.
-
Slauma over 12 years@Sander: Is this answer (stackoverflow.com/questions/2139134/…) wrong then? He says that
Parcelable
IS specifically designed for that purpose (and much faster thanSerializable
). I am a confused. -
Sander Versluys over 12 years@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.
-
Eric Leschinski over 12 yearsTo get the data back:
Bundle extras = getIntent().getExtras();
String val = extras.getString("fname");
-
JibW about 12 yearsIt was really helpfull for me. Thanks... But when receiving the passed object, the syntax Should be [ Deneme dene = (Deneme)i.getSerializableExtra("sampleObject"); ] ... Is it ???
-
Steven Elliott almost 12 yearsI 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 almost 12 years
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 oneParcelable
? It would make more sense to useSerializable
instead. When you implementParcelable
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. -
Umair over 11 yearsGood 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.
-
Gaurav Arora over 11 years
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 -
Admin over 11 years@aez Because it's sloppy from a design viewpoint and will break horribly if the Intent is ever in another process.
-
Ryan R over 11 yearsYou 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.
-
Shajeel Afzal almost 11 years@MustafaGüven But i am getting
classCastException: java.lang.Long
by doing so. Can you please explain why? -
Mustafa Güven almost 11 yearsThere is no any relation with my answer. It's very different thing you are getting. Could you share your codes?
-
James Roeiter over 10 yearsIts an overkill , gson is just a type of string serialization to json , its better to implement Serializable or Paracable .
-
none about 10 yearsif 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 developerphil.com/parcelable-vs-serializable
-
Dr. aNdRO about 10 yearsWhat if my object contains nested Arraylist?
-
VH-NZZ about 10 yearsWell 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 useSerializable
. -
Steven Mark Ford almost 10 yearsI 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.
-
Steven Mark Ford almost 10 yearsSerializable is too slow for large POJOs. Using a Bus is a much better pattern.
-
Steven Mark Ford almost 10 yearsParcelable 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.
-
Steven Mark Ford almost 10 yearsThis can quickly become infeasible for large POJOs. Rather use a Bus. See my post below.
-
Steven Mark Ford almost 10 yearsCute but don't re-invent the wheel. Bus pattern is elegant and more powerful. See my post below.
-
Steven Mark Ford almost 10 yearsSerializable is too slow for large POJOs. Using a Bus is a much better pattern.
-
MJB almost 10 yearsas 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.
-
TimJowers2 over 9 yearsOtto 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).
-
Alston over 9 yearsWhy should I have to prefix
(Serializable)
to the object? -
Mustafa Güven over 9 yearssimple. it's because of transmission. you have to look for the detailed explanation of serialization and its purpose in java (same in c#)
-
Zapnologica over 9 yearsWhy 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?
-
AK Joshi over 9 years..Check your code you are passing "bundle" as key for put cust obj & getting from "class" ..pls use one key either "class" or "bundle" ..
-
Chris McCabe over 9 yearsI 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 over 9 yearsSometimes 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.
-
Renato Probst over 9 yearsTheres 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.
-
gilsaints88 over 9 yearsI 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.
-
gilsaints88 over 9 yearsJust 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.
-
nurgasemetey over 9 yearsI would also recommend using gson because gson can also serialize arraylists in addition to above.
-
Yaroslav about 9 yearsThat's how it should look like: one statement to put, one statement to get, not dozens of lines of boilerplate error-prone code.
-
afrish about 9 yearsAccording to this benchmark bitbucket.org/afrishman/androidserializationtest Serializable is much faster than Parcelable. Please stop sharing this 5 year old nonsense about Parcelable.
-
uesports135 about 9 yearsThis 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 about 9 yearsIf 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.
-
Giridhar Karnik almost 9 yearsThere 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 almost 9 yearsThis is a hack. Sometimes we have to hack code, but not when there are other better ways of doing it.
-
Muhammad Saqib over 8 yearsGood 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 over 8 yearsyeah the original question asked to pass one object to another activity, not an array. there are more efficient and better solutions for that.
-
CommonSenseCode over 8 yearsprefer this implementation parceable is so annoying to use and difference is not noticeable for small objects
-
Justin about 8 yearsAs it stands, this answer is almost link-only. Can you add some example code or something into this answer itself?
-
breakline about 8 yearsHow 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.
-
Chad Bingham about 8 yearsThis 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
-
JamEngulfer about 8 yearsSo 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?
-
SkidRunner almost 8 yearsSorry I did not see that you had binding in your answer as well I feel that your answer is also very elegant.
-
jose920405 over 7 yearsI have a problem with
Gson
--> here stackoverflow.com/questions/39535222/problems-with-gson-library -
Amitsharma over 7 yearscan you please explain or elaborate more
-
Amitsharma over 7 yearsHomeworkData 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 over 7 yearsinside of homeworkData i am having some values these are come to add
-
OlivierH about 7 yearsLink to the article is dead. Still available on webarchive : web.archive.org/web/20160917213123/http://…
-
Mauker almost 7 yearsIt's a shame that the link is down :(
-
guru_007 almost 7 yearsbut , when implementing Parcelable interface ,and receiving through Receiver am getting RuntimeException .
-
Ojonugwa Jude Ochalifu almost 7 yearsThis is the "best" option. Some classes are so simple, you don't need to over complicate their implementation by implementing serializable
-
Woppi over 6 years@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
inRoomsActivity
-
JuliuszJ over 6 yearsThe 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 over 6 years@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.
-
Jossef Harush Kadouri about 6 yearsIMHO, thinking developer experience, I go with this solution. I don't mind paying the minor cost of converting my simple
pojo
tojson
while keeping the representing class as simple as possible. -
Steven Mark Ford almost 6 yearsI have taken the link to my blog away for now. Until I decide to re-instate my blog.
-
Salvador almost 6 yearsWhen the receiving Activity is recreated (eg on screen rotation)
obj
becomesnull
. To avoid this,obj
should be stored somewhere to get it again. Indeed the Json solution stores object data in Intent. -
john ktejik over 5 yearsIsn't gson slower than serialize?
-
Arul about 5 yearsI face Error: Parcelable encountered IOException writing serializable object
-
ByWaleed about 5 yearsParcelable is the fastest and with this generator (parcelabler.com), you can paste your class and it can generate the code for you. Simple.
-
karan about 5 yearsWow.... This man's 1st method is tremendous..... When you have very big/larger sized objects that works well
-
Randy almost 5 yearsThe Kotlin method is getString, not getStringExtra, but it won't let me edit the answer because edits have to be at least 6 characters
-
Yo Apps almost 5 years@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 almost 5 years@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.
-
Krishnabhadra over 4 yearsUpvoted 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
-
Vladimir Tolstikov over 4 yearsThanks a lot for ObjectWrapperForBinder method, really helps!
-
Gauthier almost 4 yearsThis methods are really excellent: light and straightforward. I just had to check the API level on runtime as putBinder needs level 18. I have done it with something like (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) and it works like a charm. I am using method 1.
-
dantechguy over 3 years@afrish dead link, see archive for results: "3.6 times faster than Parcelable for writes and about 1.6 times faster for reads"
-
Chris.Jenkins over 2 yearsPlease use
Parcelable
, it's about 10x faster to pass through process boundaries than Serializable. -
Subhajit Roy over 2 yearsThank you for your support. I learn about it and upgrade it.
-
Rekijan Kileren about 2 yearsNice, works with implements Parceable as well.
-
GeneCode about 2 yearsTerrible answer. With pseudocode. Just give the code. Psh
-
sp_nz about 2 yearsGson is the cleanest way. I started using Parcelable, but it's awful - way too much code needs to be added to the data classes. The data classes shouldn't need to worry about passing objects around.