Android - save value of member field in Fragment class

若如初见. 提交于 2019-12-02 15:12:45

问题


I'm trying to do something using a boolean in a Fragment class each time the Fragment is displayed.

Example

My app launches, opens the FirstFragment and the boolean for the first time is always true, then I have an if clause that checks its value:

if (FirstTime) {
    FirstTime = false;
} else {
    // Other stuff here, cause it's not true.
}

Then, on the first time, when FirstTime is true, I do stuff like go to another Fragment. and when I return to Fragment1 and on my onCreate(), I do the same. It's always true, seems that it's refreshing or something.

Then I thought that could be a problem with Fragment, and every time I press on Fragment1, it restarts or something. Then, I've added a getter and setter in my MainActivity:

public Boolean getFirstTime() {
    return FirstTime;
}

public void setFirstTime(Boolean FirstTime) {
    this.FirstTime = FirstTime;
}

where since the start, it's true and then, I changed my code from Fragment1 for:

if (((MainActivity) getActivity()).getFirstTime())
    ((MainActivity) getActivity()).setFirstTime(false);
} else {
    // Other stuff here, cause it's not true,
}

However, it's still saying that's true.

What I'm doing wrong or what I misunderstood about Fragments?
Is there any way to do it?


回答1:


You have made an assumption that the Fragment instance remains in existence as long as the app is alive. It is a reasonable assumption, and your approach would work fine if that assumption were true.

Unfortunately, a Fragment is destroyed when it recedes into the background, and created anew when it returns to the foreground. This is why it appears to "refresh". The same is not true of an Activity. When an Activity recedes into the background, it is not destroyed immediately. Rather, it is maintained on the current task's backstack for some time, and if it returns to the foreground, it is the same instance.

To combat this problem, there are four different ways:

  • Declare FirstTime as static. This should work. I've used this before. However, this should only be used in extreme cases when there is an absolute necessity to preserve the value of a member field, and only when no other way is available. Making a variable static leads to a classic memory leak.
  • Save the value of FirstTime in your Fragment using onSaveInstanceState():

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("FirstTime", FirstTime);
    }
    

    and retrieve the value in onCreate():

    @Override
    public void onCreate (Bundle savedInstanceState){
        super.onCreate();
        FirstTime = savedInstanceState.getBoolean("FirstTime");
    }
    
  • Declare FirstTime in a global constants class instead of putting it in the Fragment:

    public class GlobalConstants{
    
        public static boolean FirstTime = true;
        // other global constants ...
    
    }
    

    and access it in your Fragment like this:

    if (GlobalConstants.FirstTime) {
        GlobalConstants.FirstTime = false;
    } else {
        //Other stuff here cause it's not true
    }
    
  • Save the value of FirstTime in a SharedPreference:

    SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putBoolean("FirstTime", FirstTime);
    editor.commit();
    

    and retrieve its value in this way:

    SharedPreferences sp = getActivity().getPreferences(Context.MODE_PRIVATE);
    FirstTime = sp.getBoolean("FirstTime", true);
    

The first three methods will maintain the value of FirstTime while the application is alive. The fourth method will preserve the value of FirstTime beyond the lifetime of the application, i.e. when the app restarts, FirstTime will be true or false depending on what its value was last set before the app exited.

References:

1. Handling the Fragment Lifecycle.

2. Saving Key-Value Sets.

3. Visibility and Lifetime.

EDIT:

To understand how to use onSaveInstanceState(), see the following links:

1. Saving (and Retrieving) Android Instance State.

2. Once for all, how to correctly save instance state of Fragments.

3. Handling Configuration Changes.

It is confusing, but it will be useful to you once you understand it.




回答2:


Simple solution, set your boolean to a static.

This of course does not comply to the good practices of programming.

To answer you question more directly, I'm assuming that the fragments and activities get destroyed and new instances are created, hence the boolean being set to true again. As such, by making the variable static, it's state will remain across all instances of that class.



来源:https://stackoverflow.com/questions/30006667/android-save-value-of-member-field-in-fragment-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!