How to pass an object from one activity to another on Android

805,363

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();
    }
Share:
805,363
Adil Bhatty
Author by

Adil Bhatty

droid guy

Updated on July 08, 2022

Comments

  • Adil Bhatty
    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 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?

    • kimkevin
      kimkevin over 8 years
      I 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
      Lukas over 3 years
      I'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
      nhCoder over 3 years
      why 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
    Pentium10 almost 14 years
    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?
  • Alister
    Alister over 13 years
    get your data back again with: String fName = getIntent().getExtras().getInt("fname");
  • Samuh
    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
    MLQ over 12 years
    Yeah, I think I actually agree with you. Making those objects static is the better workaround if it's simply impractical to keep invoking putExtra() for every property you'd like to pass on. For example, right now, I want to pass an ArrayList that contains objects. I might as well make my ArrayList static instead.
  • Nate
    Nate over 12 years
    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
    Nate over 12 years
    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.
  • newman
    newman over 12 years
    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
    Ads over 12 years
    Miliu, fromClass fr = (fromClass) getParent(); is this what u needed?
  • Sander Versluys
    Sander Versluys over 12 years
    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...
  • newman
    newman over 12 years
    Adhava, I actually did this, but fr is null. Any idea why?
  • Ads
    Ads over 12 years
    miliu,please share your exception trace by that we can look into it.
  • Slauma
    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 than Serializable). I am a confused.
  • Sander Versluys
    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
    Eric Leschinski over 12 years
    To get the data back: Bundle extras = getIntent().getExtras(); String val = extras.getString("fname");
  • JibW
    JibW about 12 years
    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 ???
  • Steven Elliott
    Steven Elliott almost 12 years
    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
    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 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.
  • Umair
    Umair over 11 years
    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.
  • Gaurav Arora
    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
    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
    Ryan R over 11 years
    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.
  • Shajeel Afzal
    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
    Mustafa Güven almost 11 years
    There is no any relation with my answer. It's very different thing you are getting. Could you share your codes?
  • James Roeiter
    James Roeiter over 10 years
    Its an overkill , gson is just a type of string serialization to json , its better to implement Serializable or Paracable .
  • none
    none about 10 years
    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 developerphil.com/parcelable-vs-serializable
  • Dr. aNdRO
    Dr. aNdRO about 10 years
    What if my object contains nested Arraylist?
  • VH-NZZ
    VH-NZZ about 10 years
    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
    Steven Mark Ford almost 10 years
    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.
  • Steven Mark Ford
    Steven Mark Ford almost 10 years
    Serializable is too slow for large POJOs. Using a Bus is a much better pattern.
  • Steven Mark Ford
    Steven Mark Ford almost 10 years
    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.
  • Steven Mark Ford
    Steven Mark Ford almost 10 years
    This can quickly become infeasible for large POJOs. Rather use a Bus. See my post below.
  • Steven Mark Ford
    Steven Mark Ford almost 10 years
    Cute but don't re-invent the wheel. Bus pattern is elegant and more powerful. See my post below.
  • Steven Mark Ford
    Steven Mark Ford almost 10 years
    Serializable is too slow for large POJOs. Using a Bus is a much better pattern.
  • MJB
    MJB almost 10 years
    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.
  • TimJowers2
    TimJowers2 over 9 years
    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).
  • Alston
    Alston over 9 years
    Why should I have to prefix (Serializable) to the object?
  • Mustafa Güven
    Mustafa Güven over 9 years
    simple. it's because of transmission. you have to look for the detailed explanation of serialization and its purpose in java (same in c#)
  • Zapnologica
    Zapnologica over 9 years
    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?
  • AK Joshi
    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
    Chris McCabe over 9 years
    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
    Brian White over 9 years
    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.
  • Renato Probst
    Renato Probst over 9 years
    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.
  • gilsaints88
    gilsaints88 over 9 years
    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.
  • gilsaints88
    gilsaints88 over 9 years
    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.
  • nurgasemetey
    nurgasemetey over 9 years
    I would also recommend using gson because gson can also serialize arraylists in addition to above.
  • Yaroslav
    Yaroslav about 9 years
    That's how it should look like: one statement to put, one statement to get, not dozens of lines of boilerplate error-prone code.
  • afrish
    afrish about 9 years
    According to this benchmark bitbucket.org/afrishman/androidserializationtest Serializable is much faster than Parcelable. Please stop sharing this 5 year old nonsense about Parcelable.
  • uesports135
    uesports135 about 9 years
    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
    El Abogato about 9 years
    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.
  • Giridhar Karnik
    Giridhar Karnik almost 9 years
    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
    infinite-loop almost 9 years
    This is a hack. Sometimes we have to hack code, but not when there are other better ways of doing it.
  • Muhammad Saqib
    Muhammad Saqib over 8 years
    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
    MJB over 8 years
    yeah the original question asked to pass one object to another activity, not an array. there are more efficient and better solutions for that.
  • CommonSenseCode
    CommonSenseCode over 8 years
    prefer this implementation parceable is so annoying to use and difference is not noticeable for small objects
  • Justin
    Justin about 8 years
    As it stands, this answer is almost link-only. Can you add some example code or something into this answer itself?
  • breakline
    breakline about 8 years
    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.
  • Chad Bingham
    Chad Bingham about 8 years
    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
  • JamEngulfer
    JamEngulfer about 8 years
    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?
  • SkidRunner
    SkidRunner almost 8 years
    Sorry I did not see that you had binding in your answer as well I feel that your answer is also very elegant.
  • jose920405
    jose920405 over 7 years
  • Amitsharma
    Amitsharma over 7 years
    can you please explain or elaborate more
  • Amitsharma
    Amitsharma over 7 years
    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
    Amitsharma over 7 years
    inside of homeworkData i am having some values these are come to add
  • OlivierH
    OlivierH about 7 years
    Link to the article is dead. Still available on webarchive : web.archive.org/web/20160917213123/http://…
  • Mauker
    Mauker almost 7 years
    It's a shame that the link is down :(
  • guru_007
    guru_007 almost 7 years
    but , when implementing Parcelable interface ,and receiving through Receiver am getting RuntimeException .
  • Ojonugwa Jude Ochalifu
    Ojonugwa Jude Ochalifu almost 7 years
    This is the "best" option. Some classes are so simple, you don't need to over complicate their implementation by implementing serializable
  • Woppi
    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 in RoomsActivity
  • JuliuszJ
    JuliuszJ over 6 years
    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
    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
    Jossef Harush Kadouri about 6 years
    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.
  • Steven Mark Ford
    Steven Mark Ford almost 6 years
    I have taken the link to my blog away for now. Until I decide to re-instate my blog.
  • Salvador
    Salvador almost 6 years
    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.
  • john ktejik
    john ktejik over 5 years
    Isn't gson slower than serialize?
  • Arul
    Arul about 5 years
    I face Error: Parcelable encountered IOException writing serializable object
  • ByWaleed
    ByWaleed about 5 years
    Parcelable is the fastest and with this generator (parcelabler.com), you can paste your class and it can generate the code for you. Simple.
  • karan
    karan about 5 years
    Wow.... This man's 1st method is tremendous..... When you have very big/larger sized objects that works well
  • Randy
    Randy almost 5 years
    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
  • Yo Apps
    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
    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
    Krishnabhadra over 4 years
    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
  • Vladimir Tolstikov
    Vladimir Tolstikov over 4 years
    Thanks a lot for ObjectWrapperForBinder method, really helps!
  • Gauthier
    Gauthier almost 4 years
    This 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
    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
    Chris.Jenkins over 2 years
    Please use Parcelable, it's about 10x faster to pass through process boundaries than Serializable.
  • Subhajit Roy
    Subhajit Roy over 2 years
    Thank you for your support. I learn about it and upgrade it.
  • Rekijan Kileren
    Rekijan Kileren about 2 years
    Nice, works with implements Parceable as well.
  • GeneCode
    GeneCode about 2 years
    Terrible answer. With pseudocode. Just give the code. Psh
  • sp_nz
    sp_nz about 2 years
    Gson 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.