-1

I want to add “night” and “light” modes in my program but i don’t understand one thing. if I save the user's transition from "bright" to "night" via shared preferences. Wouldn’t the app data get bigger every time the user selects the “dark” mode during the “light” night? Need to clear shared preferences? (What is the code if necessary?). thank you very much everyone.

Syed Rafaqat Hussain
  • 1,009
  • 1
  • 9
  • 33

3 Answers3

0

It depends how you implement your shared preferences. Usually it's not a concern.

If you use the same key every time for writing the preference, the old value gets replaced, not appended. This is what you would normally do anyway with shared prefs.

Only if you use different keys, their values are stored separately and the preferences file keeps growing.

laalto
  • 150,114
  • 66
  • 286
  • 303
0

No, every time you put a value in your SharedPreferences with the same key, it is going to override it.

For example, here is some code:

SharedPreferences sp=getSharedPreferences("yourSharedName",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();

editor.putString("mode","bright"); //mode string= bright
editor.putString("mode","night"); //mode string=night, no more bright!
editor.commit(); //This is to save your choice.

They key is "mode", so everytime you assign it a value, it gets overrided.

Stefano Leone
  • 635
  • 5
  • 14
0

you have to save the preference value after change the value from light to dark and vice a versa

fun saveTheme(context: Context?, themeName: String?) {
    val mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
    val editor = mSharedPreferences.edit()
    editor.putString(Constants.DEFAULT_THEME, themeName)
    editor.apply()
}