Suppose I have two Activity classes in my Android app. Inside Activity B, I know that Activity A exists and is instantiated. What's the proper way to access Activity object A from Activity object B?
2
- I know it's probably not my business, but I can't keep from asking: what do you want to do?bigstones– bigstones2011-03-08 19:01:04 +00:00Commented Mar 8, 2011 at 19:01
- You don't. What problem are you trying to solve?Cheryl Simon– Cheryl Simon2011-03-08 19:26:23 +00:00Commented Mar 8, 2011 at 19:26
Add a comment |
2 Answers
How can you know Activity A is still around? You can't, the OS handles that and you should not assume to know anything about another activity other than the one that's in the foreground.
If you want to pass data around, use Intents or in some cases, just use static variables.
4 Comments
Ken Kinder
Ok, is there a proper place to store application-wide state variables between activities?
Andrew White
Static variables live as long as the process is around but a process can be killed at anytime after any of your activities leaves the foreground. Preferences/local-files storage are meant to store values that are meant to be persistent and application wide.
Ken Kinder
Thanks. Just one thing -- I actually want the variables not to persist after neither activity is active. Is there a recommended place to store application-wide transient data? Like preferences, but not persistent. (Though I guess I could wipe certain preferences data when the application starts.)
Andrew White
Then you want to use static variable.
You cannot access the activity directly. The only mechanism of passing data between activities is Intent mechanism.
2 Comments
Johann
Not true at all. During onCreate within an activity, the activity can store a reference of itself to a static variable in a separate class. Any other class can reference that instance and then even access any interfaces implemented by the class. I do this throughout my application.
takesavy
When the Activity is finished the ref to activity will remain active in the static variable holding the activity reference and gc will not free it ?