Pass object to another activity (without Parcelable?)

1k Views Asked by At

I need to pass object user to another activity. I know I should use Parcelable, but I can't edit User class, because it is used from maven repository.

Is it here any other way how can I pass user object? Or how to locally edit class from maven repository?

3

There are 3 best solutions below

0
On BEST ANSWER

You can use the Application class for this purposes. what you need is:

  1. create a class which derives from Application.
  2. declare the class in the AndroidManifest.xml (see here)
  3. create a object variable of type User in it (also getter and setter).
  4. assign the user object in first activit through:

    MyApplication app = (MyApplication) getApplication(); app.setUser(user);

  5. retrieve the object in other activity through:

    MyApplication app = (MyApplication) getApplication(); User user = app.getUser();

BUT: take care, after you restart you app (go in background and open it again), a new Application object will be created, where the User is null, take care of that then.

This problem can be read here.

Hope this helps.

0
On

You can serialize the object into some kind of string representation. The easiest way to do this is to convert the object into a JSON string, pass the string to the other activity via intent and convert the string back into the original object.

0
On

What I am doing is just converting the object into Json and then sending as a String using Intent. Then you can't catch it and parse Json.

P.S. Using google's Gson class making this very easy. https://code.google.com/p/google-gson/