Using SharedPreferences in Android with Kotlin: A Beginner’s Guide
SharedPreferences is a simple way to store key-value pairs in Android using the XML format. It can be used to store small amounts of data that should persist even when the application is restarted.
In this article, we will be discussing how to use SharedPreferences in Android using Kotlin code snippets.
Initializing SharedPreferences
To start using SharedPreferences, you first need to initialize it in your Activity or Fragment. To do this, use the following code:
val sharedPreferences = getSharedPreferences("prefs", Context.MODE_PRIVATE)
The first argument of the getSharedPreferences()
method is the name of the preferences file, and the second argument is the mode in which the preferences file should be opened. In this case, we are using Context.MODE_PRIVATE
, which means the preferences file will be private to the app.
Storing values in SharedPreferences
Once you have initialized SharedPreferences, you can start storing values. To store a value, use the following code:
sharedPreferences.edit().putString("key", "value").apply()
The putString()
method takes two arguments: the key and the value. In this case, we are storing a string value, but you can also store other data types such as integers, booleans, and floats.
Retrieving values from SharedPreferences
To retrieve a value from SharedPreferences, use the following code:
val value = sharedPreferences.getString("key", "default value")
The getString()
method takes two arguments: the key and a default value. If the key doesn't exist, the default value will be returned.
Removing values from SharedPreferences
To remove a value from SharedPreferences, use the following code:
sharedPreferences.edit().remove("key").apply()
The remove()
method takes one argument: the key of the value to be removed.
Conclusion
In this article, we have discussed how to use SharedPreferences in Android using Kotlin code snippets. We have covered how to initialize SharedPreferences, store values, retrieve values, and remove values.
SharedPreferences is a simple and effective way to store small amounts of data in Android. With its XML format, it is easy to understand and use. If you are working on an Android app and need to persist data, SharedPreferences is definitely worth considering.