Android SharedPreferences in Kotlin - Data Storage


Storing and managing app-specific data is crucial in Android development. Android SharedPreferences is a lightweight and simple way to store key-value pairs for your app. In this guide, we'll explore how to use SharedPreferences in Kotlin for data storage.


Using SharedPreferences

To use SharedPreferences, you can obtain an instance of it for your app's context. Here's an example of how to save and retrieve data:

// Get a reference to SharedPreferences
val sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE)
// Saving data
val editor = sharedPreferences.edit()
editor.putString("username", "John")
editor.putInt("score", 100)
editor.apply()
// Retrieving data
val username = sharedPreferences.getString("username", "DefaultUsername")
val score = sharedPreferences.getInt("score", 0)

In this code, we create or access a SharedPreferences instance named "myPreferences" and use it to save and retrieve data.


Editor for SharedPreferences

The SharedPreferences editor allows you to modify the data stored in SharedPreferences. You can use it to put, update, or remove key-value pairs. Here's how you can use the editor:

val editor = sharedPreferences.edit()
// Storing data
editor.putString("email", "john@example.com")
editor.putInt("level", 5)
// Updating data
editor.putString("email", "updated@example.com")
// Removing data
editor.remove("level")
editor.apply()

The editor must be applied using `apply()` or `commit()` to save the changes to SharedPreferences.


Conclusion

Android SharedPreferences provides a simple and efficient way to store app-specific data. Whether you need to store user preferences, game scores, or other settings, SharedPreferences in Kotlin is a handy tool for data storage in Android apps.


Happy coding!