How does SharedPreferences work internally in Android SDK?

SharedPreferences is a lightweight mechanism in Android for persisting simple data types. It provides a way to store and retrieve key-value pairs, which can be used to save user preferences, settings, or application states. Internally, SharedPreferences uses an XML file to store the data in the app's private directory, making it accessible only to the app itself.

When you write to SharedPreferences, the data is committed to memory and can be retrieved later, even if the app is closed or the device is rebooted. This makes SharedPreferences ideal for storing small amounts of data that need to be persistent across sessions.

How SharedPreferences Works Internally

When you first use SharedPreferences in your Android application, the system creates an XML file in the app’s data directory (usually located at /data/data//shared_prefs). Each entry is stored as a key-value pair in this XML format. Here's a simplified version of how SharedPreferences handles data:

  • Get Preferences: When you call getSharedPreferences(), Android retrieves the XML file corresponding to the given name.
  • Storing Data: When you store data using edit().putString(), it updates the in-memory representation of the data.
  • Commit Changes: When commit() or apply() is called, the changes are written to the XML file.
  • Retrieve Data: You can retrieve stored data using methods like getString(), which reads from the XML file.

Example Usage of SharedPreferences

SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); // Storing data editor.putString("username", "john_doe"); editor.putInt("user_age", 30); editor.apply(); // or editor.commit(); // Retrieving data String username = sharedPreferences.getString("username", null); int userAge = sharedPreferences.getInt("user_age", 0);

SharedPreferences Android data storage key-value pairs user preferences application state