Daily there are many questions of the following type on SO:
How do I get a variable from another
Activity
?
The answers usually recommend to use SharedPreferences
or Intent.putExtra()
.
To me, a getter
method is what would be an approach to access a variable from another class. After all, the Activity
that is under consideration is a class, and it's variables are class members.
Why aren't getter methods preferred to approaches like SharedPreferences or Intent extras?
I'm talking about simple situations that require accessing a variable between activities, for example this one:
class OneClass extends Activity {
int a;
..
// some changes to a
..
}
And then in another class(Activity
):
class SomeOtherClass extends Activity {
..
// trying to access a here
..
}
Is a getter
method a correct approach here, or not?
Again - I'm not talking about scenarios where these things are actually the right way to go. SharedPreferences
for persistent storage of small amount of data, extras
as the documentation says : This can be used to provide extended information to the component. For example, if we have a action to send an e-mail message, we could also include extra pieces of data here to supply a subject, body, etc.
As some of the answers have likely indicated that there are certain scenarios like no guarantee of the other Activity
being alive, I guess there are more probable and correct reasons as to why people suggest going for intents and shared preferences.
The answer to your question is two fold:
The simple answer is because the Activity
life cycle is controlled by the Android OS. Activities are unlike normal classes which are instantiated by the user code and are guaranteed to be available till they are no longer referenced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With