Skip to content
DeveloperMemos

Observing SharedPreferences Changes in Android

Android, SharedPreferences, Kotlin1 min read

In Android development, managing app data efficiently is crucial for a seamless user experience. SharedPreferences provide a handy way to store key-value pairs persistently. However, monitoring changes to these preferences can be equally important - especially when you need to react to modifications or synchronize UI elements accordingly. In this article, we will explore how to observe SharedPreferences changes in Android using Kotlin.

Setting Up SharedPreferences

Before diving into observing changes, let's quickly review how to work with SharedPreferences in Android. To get started, you typically obtain a reference to the default SharedPreferences instance associated with your app:

1val sharedPreferences = getSharedPreferences("my_preferences", Context.MODE_PRIVATE)

With the sharedPreferences reference in hand, you can read from and write to SharedPreferences using functions like getString(), putString(), getInt(), putInt(), and so on.

Observing SharedPreferences Changes

To observe changes in SharedPreferences, we can leverage SharedPreferences.OnSharedPreferenceChangeListener. This interface allows us to listen for changes in specific keys within the SharedPreferences file.

Here's how you can set up a listener to monitor changes:

1val listener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
2 if (key == "my_key") {
3 // React to the change in 'my_key'
4 val value = sharedPreferences.getString(key, "")
5 // Update UI or perform necessary actions
6 }
7}
8
9sharedPreferences.registerOnSharedPreferenceChangeListener(listener)

In this example, we create an OnSharedPreferenceChangeListener instance that triggers when the specified key ("my_key") changes. Inside the listener, you can retrieve the updated value and proceed to update any relevant UI components or execute required logic based on the change.

Removing the Listener

Remember to unregister the listener when it's no longer needed to prevent memory leaks. You can do this in the onDestroy() method of your activity or fragment:

1override fun onDestroy() {
2 super.onDestroy()
3 sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener)
4}