Search code examples
javaandroidandroid-studiojreddit

Pass object to another activity (without Parcelable?)


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?


Solution

  • 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.