How to keep button state same when fragment is destroyed and created?

How to keep button state same when fragment is destroyed and created?
0

#1

I have a button in a fragment, called homeFragment, which has an activity that has a switch. Now I initialized the switch, in onCreateView of the fragment like this:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View RootView = inflater.inflate(R.layout.fragment_home, container, false);
        protectionSwitch = (Switch)RootView.findViewById(R.id.main_switch_protection);

Now I want to store the state of the switch in a SharedPreferences value. But I stored the value like this:


isEnabledState = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = isEnabledState.edit();
    editor.putBoolean(ENABLEDGETKEY, true);
    editor.apply();
Boolean isEnabled = true;

Now I’m trying to get this value back when I launch the app again after the fragment is destroyed and also restore the switch position like this, in onCreateView:

SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences(ENABLEDGETKEY, Context.MODE_PRIVATE);
    isEnabled = sharedPreferences.getBoolean(ENABLEDGETKEY, false);
    if (isEnabled) {
        protectionSwitch.setChecked(true);
    }
    else {
        protectionSwitch.setChecked(false);
    }

But this doesn’t work. Instead, I simply get the button to stay in disabled position.

What can I do, to keep the switch position the same even when the fragment is destroyed an launched again.


#2

Hey @sntdevco,
I noticed in your code that you use getPreferences to write to the preferences and getSharedPreferences to read from them.
I would suggest reading here regarding the differences between them. This might be relevant to your situation since you are creating and destroying fragments and since you have not mentioned otherwise, in different activities.

Hope that helps.


#3

I got that fixed - thanks for your help!