Shared Preferences in Android is a mechanism for storing key-value pairs of primitive data types in a private file. It provides a way to persist simple data across application sessions without the need for a database. In Kotlin, Shared Preferences are often used to save application settings, user preferences, or any other small pieces of data that need to be persisted.
Overview
Shared Preferences are represented by the SharedPreferences
interface in Android, and you typically interact with it through an instance of SharedPreferences
. Data is stored in the form of key-value pairs, where keys are String
s, and values can be of types such as String
, Int
, Boolean
, Float
, and Long
.
Properties and Methods
Obtaining SharedPreferences
To get an instance of SharedPreferences
, you generally use the getSharedPreferences()
method, specifying the name of the preferences file and the mode in which the file should be opened.
val sharedPreferences = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
Context.MODE_PRIVATE: The default mode, where the created file can only be accessed by the calling application.
Reading from SharedPreferences
You can read values from SharedPreferences
using various getter methods. These methods require a key and a default value, which is returned if the key is not found.
val myString = sharedPreferences.getString("myKey", "defaultString")
val myInt = sharedPreferences.getInt("myIntKey", 0)
val myBoolean = sharedPreferences.getBoolean("myBooleanKey", false)
val myFloat = sharedPreferences.getFloat("myFloatKey", 0.0f)
val myLong = sharedPreferences.getLong("myLongKey", 0L)
Writing to SharedPreferences
To write data to SharedPreferences
, you use an instance of SharedPreferences.Editor
. You obtain an editor by calling edit()
on a SharedPreferences
instance.
val editor = sharedPreferences.edit()
editor.putString("myKey", "newValue")
editor.putInt("myIntKey", 10)
editor.putBoolean("myBooleanKey", true)
editor.putFloat("myFloatKey", 1.23f)
editor.putLong("myLongKey", 100L)
editor.apply()
apply(): Asynchronously commits the changes to the in-memory SharedPreferences
instance and eventually to the disk. This is the preferred way as it is faster and does not block the main thread.commit(): Synchronously commits the changes and returns a Boolean
indicating success or failure. This blocks the main thread, so it’s generally discouraged.
Removing Data
To remove a key-value pair from SharedPreferences
, use the remove()
method on the Editor
.
editor.remove("myKey")
editor.apply()
To clear all data from SharedPreferences
, use the clear()
method.
editor.clear()
editor.apply()
Example
Here is a complete example demonstrating how to use SharedPreferences
in a Kotlin Android application:
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Get SharedPreferences instance
val sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
// Write data to SharedPreferences
val editor = sharedPreferences.edit()
editor.putString("username", "JohnDoe")
editor.putInt("age", 30)
editor.putBoolean("isLoggedIn", true)
editor.apply() // Apply changes asynchronously
// Read data from SharedPreferences
val username = sharedPreferences.getString("username", "defaultUser")
val age = sharedPreferences.getInt("age", 0)
val isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false)
// Use the retrieved values
println("Username: $username")
println("Age: $age")
println("Is Logged In: $isLoggedIn")
// Remove a specific key-value pair
editor.remove("age")
editor.apply()
// Clear all data
editor.clear()
editor.apply()
}
}
Summary
Shared Preferences in Android Kotlin is a lightweight way to store simple data in key-value pairs. The main properties and methods include:
- getSharedPreferences(): To obtain a
SharedPreferences
instance. - getString(), getInt(), getBoolean(), getFloat(), getLong(): To read data.
- edit(): To obtain an
Editor
for writing data. - putString(), putInt(), putBoolean(), putFloat(), putLong(): To add or update data.
- apply(), commit(): To save changes.
- remove(): To delete specific data.
- clear(): To remove all data.
Using these methods, you can efficiently manage small pieces of data in your Android applications.