Why aren't getters preferred when accessing va

2020-06-09 07:21发布

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.

标签: java android
10条回答
对你真心纯属浪费
2楼-- · 2020-06-09 07:49

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.

查看更多
放荡不羁爱自由
3楼-- · 2020-06-09 07:55

You are right when it comes to basic Class structure. However if, you consider activity lifecycle and memory management keeping whole activity alive for accessing small amount of data is not logical.

查看更多
走好不送
4楼-- · 2020-06-09 07:56

The situation is slightly more complicated than you suggest. If you are simply writing classes that exist inside the life cycle of an activity, and you want them to access certain members of the activity, than you could easily use getters and typical java paradigms.

That being said, Android does not contain some natural mechanism to access the instance of another Activity. This is probably very intentional. Activities are meant to operate in a distinct fashion. The closest comparison is that each Activity is meant to be like a page on a website (so referencing another instance of a page wouldn't make much sense).

查看更多
你好瞎i
5楼-- · 2020-06-09 07:58

To use your example, the first problem that you have is how to pass a reference to an instance of OneClass to SomeOtherClass. SomeOtherClass would need a reference to the instance of OneClass in order to call oneClass.getVariable(). There is no easy way to do this because when an Activity starts another Activity it does it by calling startActivity() and passing an Intent. That's the mechanism that you have readily available for passing parameters to an Activity when you start it, which is why you should probably use it.

Following on your example, another choice would be to use a static (class) variable to hold the data you want to pass between activities. So you could do something like this:

class OneClass extends Activity {
    private static int a;

    public static int getA() {
        return a;
    }

    ..
    // some changes to a
    ..
}

class SomeOtherClass extends Activity {
    ..
    // trying to access a here
    int myA = OneClass.getA();
}

However, this pretty much assumes that there will be only one instance of OneClass and that's where it all breaks down IMHO. In Android, activities get created and destroyed all over the place. There can be several instances of an activity at any given time and you never know how many you have or which one is the currently active one. That makes static variables inside Activity classes difficult to get right. For passing data between activities I would use the Extras in Intent, because it is clear that you are passing data when starting an Activity. It is self-documenting.

On the other hand, if you have data that is really global for your whole application, then I would just use static (class) variables in some class that is accessible from all classes directly. Some people subclass Application to do this, but the documentation indicates that you don't have to and in general you don't have to. You can just do something like this:

public class Globals {
    public static int a; // Publicly available, don't need getter
}

Then, any class can just store something in Globals.a or access it. You don't need to subclass Application for this.

查看更多
Emotional °昔
6楼-- · 2020-06-09 07:59

Solution: An Activity is an application component, it has its life cycle and back stack unlike classes. Though we can pass objects through parceable and serialization but it is not recommended. We can pass the object through bundle in intent object or use shared preferences to access the object. Using getter wouldn't be a good idea. Or you can create a separate Constant Class and define static varaible there and then can access it.

查看更多
▲ chillily
7楼-- · 2020-06-09 08:00

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.
查看更多
登录 后发表回答