SharedPreferences is a way to store key-value pairs in Android applications, persisting data even after the app is closed. It's often used to store simple app settings, user preferences, and other lightweight data.
Here's a step-by-step example of how to use SharedPreferences in a Kotlin Android app: Create or Open SharedPreferences: To start using SharedPreferences, you need to obtain an instance of it. You usually do this in your app's Activity or Fragment.
val sharedPref = getSharedPreferences("my_app_prefs", Context.MODE_PRIVATE)
In this example, "my_app_prefs" is the name of the SharedPreferences file, and Context.MODE_PRIVATE ensures that only your app can access this SharedPreferences file. Writing Data to SharedPreferences: You can write data to SharedPreferences using its various put methods. For example:
val editor = sharedPref.edit() editor.putString("username", "john_doe") editor.putInt("age", 25) editor.apply() // or editor.commit()
Here, we're storing a username and age as key-value pairs. Reading Data from SharedPreferences: You can read data from SharedPreferences using its various get methods. For example:
val username = sharedPref.getString("username", "") val age = sharedPref.getInt("age", 0)
Here, "username" and "age" are the keys used to retrieve the corresponding values. The second argument in these methods is the default value that will be returned if the key doesn't exist. Updating Data in SharedPreferences: To update data, you simply write it again using the same keys:
val editor = sharedPref.edit() editor.putString("username", "new_username") editor.putInt("age", 26) editor.apply()
Deleting Data from SharedPreferences: To remove a specific key-value pair from SharedPreferences:
val editor = sharedPref.edit() editor.remove("username") editor.apply()
Clearing All Data from SharedPreferences: To remove all data from the SharedPreferences file:
val editor = sharedPref.edit() editor.clear() editor.apply()
Assuming you have a TextView in your layout XML file:
<TextView android:id="@+id/usernameTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Username: " android:textSize="16sp"/>
Here's how you would show the stored username in your activity:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sharedPref = getSharedPreferences("my_app_prefs", Context.MODE_PRIVATE) val username = sharedPref.getString("username", "") val usernameTextView = findViewById<TextView>(R.id.usernameTextView) usernameTextView.text = "Username: $username" } }
Remember that apply() is asynchronous and is preferred for most cases, while commit() is synchronous and can be used when you need immediate results. That's it! This is a basic example of how to use SharedPreferences in Kotlin for Android app development. You can adapt this approach to suit your specific use case and requirements.