Junior — Middle
How is the data storage mechanism implemented and used in Android applications using SharedPreferences?
sobes.tech AI
Answer from AI
SharedPreferences in Android is a mechanism for storing simple key-value pairs, typically used for saving settings or small data.
Main points:
- Data is stored in an XML file accessible only to your app.
- Supported types: String, int, boolean, float, long.
- Uses the SharedPreferences object and the SharedPreferences.Editor for operations.
Example usage:
// Getting SharedPreferences object
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
// Reading a value
String username = prefs.getString("username", "defaultUser");
// Writing a value
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", "newUser");
editor.apply(); // or commit()
apply() saves changes asynchronously, commit() synchronously and returns a boolean result.
Thus, SharedPreferences is convenient for storing small settings and data that do not require complex structures.