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条回答
\"骚年 ilove
2楼-- · 2020-06-09 08:11

I don't think this is somehow unique to Android. Any relatively sophisticated Java-based framework has higher-level 'rules' like this.

  • Java's Swing or AWT restrict you from calling certain methods from certain threads.
  • Java ME works very much like Android in this respect.
  • In Java EE -- forget about trying to share anything across Servlets or EJBs with static members. They aren't even on the same machine, maybe.

To directly answer your question: you can't simply access objects "freely" in the same way you might in a simple Java program since some assumptions that that depends on break down, namely, that these objects are even in the same ClassLoader.

查看更多
萌系小妹纸
3楼-- · 2020-06-09 08:14

This would work perfectly if the program could control when activities are created and destroyed. But the problem is that they are managed by the OS.

You can store a reference to another activity. Only what will happen if it gets destroyed or recreated? You will have a reference to the class instance which is longer relevant with no reliable means to detect this case.

Shared preferences and intents are used in these cases because they are state-independent. No matter what happens to any activity, preferences will always be available in the state they were. Intent is also an object which exists by itself and won't get stale.

查看更多
Rolldiameter
4楼-- · 2020-06-09 08:16

I believe the reason that Activities dont have have getters and setter is related to the lifecycle of an Activity. You really shouldn't guarantee that other Activities are alive since if they are not onScreen the system can clean them up at any give time.

However, to follow your pattern, you extend Application and use getters and setters for that. How to declare global variables in Android?

查看更多
姐就是有狂的资本
5楼-- · 2020-06-09 08:16

Mainly because the whole process of sending an intent is not that simple. An intent can travel through the system, between processes etc... in short the object you created is not the same object that is received at the end (this can be proven if trying to extend an intent class, send it to another activity and try to cast it back to your extended class on the other end, its simply not the same object).

Now i also really hate this, thats why i have created some base classes that help me work with intents (i call them BundleWrappers) which would work something like this:

you create a POJO with getters/setters, you fill that object and use it however you like,

then when the time comes just serialize into a bunle and deserialize it into the same object on the other end.

then you will have the same object with getters and setters in the other activity as well.

The main reason intents suck is that you have to find a way to keep track of all the keys for the extras, and the additional implementation for serializing the bundle.

still even with my method its not easy to use intents but it is the best i have found so far in terms of performance and object organization.

public abstract class BundleWrapper implements Parcelable {

    protected static final String KEY_PARCELABLE = "key_parcelable";

    public static final String TAG = BundleWrapper.class.getSimpleName();

    public BundleWrapper() {
        super();
    }

    abstract Parcelable getParcelable();

    public Bundle toBundle(){
        final Bundle bundle = new Bundle();
        Parcelable parcelable = getParcelable();
        if (parcelable != null) {
            bundle.setClassLoader(parcelable.getClass().getClassLoader());
            bundle.putParcelable(KEY_PARCELABLE, parcelable);
        }
        return bundle;
    }

    public static Object fromBundle(final Intent intent) {
        return fromBundle(intent.getExtras());
    }

    public static Object fromBundle(final Bundle bundle) {
        if (bundle != null && bundle.containsKey(KEY_PARCELABLE)) {
            bundle.setClassLoader(BundleWrapper.class.getClassLoader());
            return bundle.getParcelable(KEY_PARCELABLE);
        }
        return null;
    }

}

Here is my base class, for using it you simply extend it and implement parcelable(the retarded part of the process :):

public class WebViewFragmentBundle extends BundleWrapper implements Parcelable {

    public static final String TAG = WebViewFragmentBundle.class.getSimpleName();

    private String url;
    public WebViewFragmentBundle() {
        super();
    }

    public WebViewFragmentBundle(Parcel source) {
        this.url = source.readString();
    }

    public String getUrl() {
        return url;
    }


    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    Parcelable getParcelable() {
        return this;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(url);
    }

    public static final Parcelable.Creator<WebViewFragmentBundle> CREATOR = new Parcelable.Creator<WebViewFragmentBundle>() {
        @Override
        public WebViewFragmentBundle createFromParcel(Parcel source) {
            return new WebViewFragmentBundle(source);
        }

        @Override
        public WebViewFragmentBundle[] newArray(int size) {
            return new WebViewFragmentBundle[size];
        }
    };


}

and for a use case:

public static void launchAugmentedRealityActivityForResult(final Activity context, WebViewFragmentBundle wrapper) {
        final Intent intent = new Intent(context, Augmented.class);
        intent.putExtras(wrapper.toBundle());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivityForResult(intent, AUGMENTED_RESULT_CODE);
    }

and cast it on the other end like:

(WebViewFragmentBundle)BundleWrapper.fromBundle(getIntent());
查看更多
登录 后发表回答