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.
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/
). Each entry is stored as a key-value pair in this XML format. Here's a simplified version of how SharedPreferences handles data:
getSharedPreferences()
, Android retrieves the XML file corresponding to the given name.edit().putString()
, it updates the in-memory representation of the data.commit()
or apply()
is called, the changes are written to the XML file.getString()
, which reads from the XML file.
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);
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?