The formula for shared preferences is : val sharedPreferences = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE) You create a storage cabinet, "MyAppPrefs" in this case then you use putters and getters api methods to store and retrieve the values of keys
The SharedPreferences Formula:
1. Create/Open the Storage Cabinet:
val sharedPreferences = getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE)
"MyAppPrefs" = The name of your cabinet (becomes MyAppPrefs.xml file) MODE_PRIVATE = Only your app can access this cabinet This returns a SharedPreferences object that represents your storage cabinet 2. Get an Editor (to write/modify):
val editor = sharedPreferences.edit()
Think of this as getting a pen to write in your cabinet 3. Use Setter Methods (Putters) to Store:
editor.putString("username", "JohnDoe")
editor.putInt("highScore", 1500)
editor.putBoolean("soundEnabled", true)
editor.putFloat("volume", 0.8f)
editor.apply() // Don't forget to apply!
4. Use Getter Methods to Retrieve:
val username = sharedPreferences.getString("username", "defaultUser")
val highScore = sharedPreferences.getInt("highScore", 0)
val soundEnabled = sharedPreferences.getBoolean("soundEnabled", true)
val volume = sharedPreferences.getFloat("volume", 1.0f)
Second parameter is the default value if key doesn't exist The Complete Pattern:
// 1. Create cabinet
val prefs = getSharedPreferences("MyStorage", Context.MODE_PRIVATE)
// 2. Writing (PUT)
prefs.edit().putString("key", "value").apply()
// 3. Reading (GET)
val value = prefs.getString("key", "default")
That's it! It really is that simple - create a named storage cabinet, then use put/get methods to store and retrieve your key-value pairs. The beauty is in its simplicity!