Search code examples
javaandroidsharedpreferences

Save the selected Light or night mode via sharedpreferences via RadioButton (within Radio Group)


How to save the selected Light or night mode via sharedpreferences via RadioButton (within Radio Group)?

I understand how to save plain text in sharedpreferences. But it is very unclear to me how to save night and light mode via sharedpreferences. Please tell us how to save via sharedpreferences. I want to save the printed option via RadioButton (within RadioGroup).

Thank you!


Solution

  • First you will need to save type boolean in your shared preference.

    private final SharedPreferences mSharedPreferences;
    mSharedPreferences = context.getSharedPreferences("example_name", Context.MODE_PRIVATE);
    //SAVE BOOLEAN WITH KEY AND VALUE
    mSharedPreferences.edit().putBoolean(key, value).apply();
    //GET BOOLEAN WITH KEY AND DEFAULT VALUE, IF IT DOESN'T CONTAIN IT
    Boolean myBoolean = mSharedPreferences.getBoolean(key, defaultValue);
    

    After that, on your OnStart method you need to set it up

    AppCompatDelegate.setDefaultNightMode(mSharedPreferences.getDayNightMode());