tipu
tipu

Reputation: 9604

Using static instead of parcelable/serialize -- is this bad?

I need to keep a reference to an object between different activities. The two said mentions seem to create new objects from activity to activity. This is a problem because changes to the object in the "child" activities don't persist once the parent activity gets focus. My solution to this was just to create a static getter in the parent-most activity which the child activities call and work with. Is this the incorrect way to go about this?

Upvotes: 2

Views: 787

Answers (3)

Blundell
Blundell

Reputation: 76536

You should create a Singleton, this has a single instance whenever you talk to it. (Just like your describing).

Here's one I made earlier : https://stackoverflow.com/a/6539080/413127

Upvotes: 0

Alexander
Alexander

Reputation: 48272

You can make your object persistent throughout the whole application lifecycle by making it a field in your Application-derived class.

public class MyAppication extends Application {

private Object mMyData; 

public setData(Object data) {
    mMyData = data;
}

public Object getData() {
      return mMyData;
}

}

Then ((MyApplication)getAppllication()).setData or getData()

This way you can exchange data within the application because MyApplication will always exist.

You'll also have to add MyApplcation to manifest

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234847

If you want to share a single instance of an object between activities, you can create a singleton class. The only thing wrong with using your parent-most activity class to implement the singleton might be that it might violate the single responsibility principle.

Upvotes: 3

Related Questions