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:
- For the meta aspect, which belongs on meta SO anyway, many newbie programmers see Android, want to write apps, and suck at Java.
- For the other quesiton, typically using a getter and setter won't work, because you can't pass objects between Activities in a straightforward way. While you can technically do this with a Parcelable, it's not recommended, and the better way is to use an intent to pass data between application components.
- Another point this highlights is that Android apps should keep a minimal amount of state inside components. I think this has been a big success of Android. If you look at apps out there, there is on average a lot less global state than typical programs written in java. The programs are also smaller, which is to be expected, but the fact that an atomic activity can represent the state of a single screen, and the fact that any single screen won't typically be persisting that much state across the entire app, leads to an good logical separation between app components.

