Shared Preferences in Kotlin for Android: A Comprehensive Guide with Examples
When developing Android applications, you often need to store small amounts of data persistently. This could be user preferences, app settings, or simple key-value pairs. SharedPreferences is a lightweight and efficient way to store such data in Android. In this blog post, we’ll explore how to use SharedPreferences in Kotlin, with practical examples to help you get started.
What is SharedPreferences?
SharedPreferences is an API provided by Android that allows you to save and retrieve key-value pairs of primitive data types (e.g., Int, String, Boolean, Float, Long). The data is stored in an XML file within the app’s internal storage, making it private to the application.
Key Features:
- Simple and Lightweight: Ideal for storing small amounts of data.
- Persistent Storage: Data remains available even after the app is closed or the device is restarted.
- Thread-Safe: SharedPreferences is thread-safe, so you don’t need to worry about synchronization.
Getting Started with SharedPreferences in Kotlin
To use SharedPreferences in your Kotlin Android project, follow these steps:
1. Accessing SharedPreferences
You can access SharedPreferences using the getSharedPreferences() method or the PreferenceManager.getDefaultSharedPreferences() method.
import android.content.Context
import android.content.SharedPreferences
// Accessing SharedPreferences using getSharedPreferences()
val sharedPreferences: SharedPreferences = context.getSharedPreferences("MyAppPreferences", Context.MODE_PRIVATE)
// Accessing default SharedPreferences
val defaultSharedPreferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
2. Writing Data to SharedPreferences
To store data in SharedPreferences, you need to use the SharedPreferences.Editor class. This class provides methods to write data and commit the changes.
// Writing data to SharedPreferences
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.putString("username", "JohnDoe")
editor.putInt("userAge", 25)
editor.putBoolean("isLoggedIn", true)
editor.apply() // or editor.commit()
apply(): Asynchronously saves the changes. It’s faster and doesn’t block the main thread.commit(): Synchronously saves the changes and returns a boolean indicating success or failure.
3. Reading Data from SharedPreferences
To retrieve data from SharedPreferences, you can use the appropriate get methods provided by the SharedPreferences class.
// Reading data from SharedPreferences
val username: String? = sharedPreferences.getString("username", "DefaultUser")
val userAge: Int = sharedPreferences.getInt("userAge", 0)
val isLoggedIn: Boolean = sharedPreferences.getBoolean("isLoggedIn", false)
- The second parameter in the
getmethods is the default value to return if the key is not found.
4. Removing Data from SharedPreferences
If you want to remove a specific key-value pair or clear all data from SharedPreferences, you can use the remove() or clear() methods.
// Removing a specific key-value pair
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.remove("username")
editor.apply()
// Clearing all data from SharedPreferences
editor.clear()
editor.apply()
5. Listening for Changes in SharedPreferences
You can register a SharedPreferences.OnSharedPreferenceChangeListener to listen for changes in SharedPreferences.
val listener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
when (key) {
"username" -> {
val newUsername = sharedPreferences.getString(key, "DefaultUser")
println("Username changed to: $newUsername")
}
"userAge" -> {
val newUserAge = sharedPreferences.getInt(key, 0)
println("User age changed to: $newUserAge")
}
}
}
sharedPreferences.registerOnSharedPreferenceChangeListener(listener)
// Don't forget to unregister the listener when it's no longer needed
sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener)
Practical Examples
Example 1: Saving and Retrieving User Settings
Let’s say you want to save the user’s theme preference (light or dark mode) and retrieve it when the app starts.
// Saving the theme preference
fun saveThemePreference(context: Context, isDarkMode: Boolean) {
val sharedPreferences = context.getSharedPreferences("AppSettings", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putBoolean("isDarkMode", isDarkMode)
editor.apply()
}
// Retrieving the theme preference
fun getThemePreference(context: Context): Boolean {
val sharedPreferences = context.getSharedPreferences("AppSettings", Context.MODE_PRIVATE)
return sharedPreferences.getBoolean("isDarkMode", false) // Default to light mode
}
Example 2: Storing User Login Information
You can use SharedPreferences to store user login information, such as a username and a token.
// Saving user login information
fun saveLoginInfo(context: Context, username: String, token: String) {
val sharedPreferences = context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putString("username", username)
editor.putString("token", token)
editor.apply()
}
// Retrieving user login information
fun getLoginInfo(context: Context): Pair<String?, String?> {
val sharedPreferences = context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE)
val username = sharedPreferences.getString("username", null)
val token = sharedPreferences.getString("token", null)
return Pair(username, token)
}
Example 3: Clearing User Data on Logout
When the user logs out, you may want to clear their data from SharedPreferences.
fun clearUserData(context: Context) {
val sharedPreferences = context.getSharedPreferences("UserInfo", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.clear()
editor.apply()
}
Conclusion
SharedPreferences is a powerful and easy-to-use tool for storing small amounts of data in Android applications. Whether you’re saving user preferences, app settings, or login information, SharedPreferences provides a simple and efficient way to manage persistent data.
In this blog post, we’ve covered the basics of using SharedPreferences in Kotlin, along with practical examples to help you implement it in your own projects. By leveraging SharedPreferences, you can enhance the user experience and ensure that your app retains important data across sessions.
Happy coding! 🚀