'SharedPreferences forgets day - night mode after a while
I ask for a little attention and dedication to my problem. Namely, I have a defined color themes (white and black) in Style for day and night mode. Then, with the help of the switch, I choose which topic will be visible. With the help of SharedPreferences I remember which topic was chosen and that's where the problem happens! When I select Night mode, SharedPreferences forgets night mode for a while, since the theme is called from Main Activity using the function and switch, the main screen is black because it is called from style, but the option menu is white because SharedPreferences forgot Night mode .
Main Activity:
super.onCreate(savedInstanceState);
if (DayNightActivity.getNightPref(this)) {
setTheme(R.style.AppTheme_Dark);
mActionBar.setTitle(Html.fromHtml(.........));
}else {
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_main);
DayNightActivity bottomSheet = new DayNightActivity();
bottomSheet.show(getSupportFragmentManager(), "BottomSheetDayNight");
DayNightActivity:
public static final String DayNightPREFERENCES = "prefsNight";
public static final String KEY_ISNIGHTMODE = "isNightMode";
private void saveNightModeState(boolean nightMode) {
SharedPreferences.Editor editor = prefsNight.edit();
editor.putBoolean(KEY_ISNIGHTMODE, nightMode);
editor.apply();
}
public void checkNightModeActivated() {
if (prefsNight.getBoolean(KEY_ISNIGHTMODE, false)){
nSwitch.setChecked(true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else {
nSwitch.setChecked(false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
public static boolean getNightPref(Context context) {
SharedPreferences prefsNight = context.getSharedPreferences(DayNightActivity.DayNightPREFERENCES, Context.MODE_PRIVATE);
return prefsNight.getBoolean(DayNightActivity.KEY_ISNIGHTMODE, false);
}
@Override
public void onDestroyView () {
super.onDestroyView();
Intent intent = new Intent(getContext(), VoiceRecognitionActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_ANIMATION);
getActivity().finish();
startActivity(intent);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
