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.