Android: Storing, Retrieving & Editing Values with SharedPreferences
Android provides a way to store and retrieve key-value pairs using the SharedPreferences API. This is a simple and efficient way to persist data across app sessions without the need for a database or file storage.
To store a value, you first need to get an instance of the SharedPreferences class:
SharedPreferences preferences = getSharedPreferences("myPrefs", MODE_PRIVATE);
The first parameter is the name of the preferences file, and the second parameter is the mode, which determines the accessibility of the preferences file.
Once you have a SharedPreferences instance, you can use its edit() method to obtain an instance of the Editor class:
SharedPreferences.Editor editor = preferences.edit();
The Editor class provides methods for adding key-value pairs:
editor.putString("name", "John"); editor.putInt("age", 30); editor.putBoolean("isMarried", true);
Finally, you need to commit the changes:
To retrieve a value, you just need to call the appropriate method on the SharedPreferences instance:
String name = preferences.getString("name", ""); int age = preferences.getInt("age", 0); boolean isMarried = preferences.getBoolean("isMarried", false);
The second parameter of each method is the default value to use if the key is not found in the preferences file.
To edit a value, you can simply call the appropriate put method with the new value, followed by a commit:
editor.putString("name", "Jane"); editor.commit();
Note that you must call commit() to save the changes.
In conclusion, SharedPreferences provide a simple and efficient way to store and retrieve key-value pairs in Android. By using this API, you can easily persist data across app sessions without the need for a database or file storage.