SharedPreferences Tutorial
Introduction to SharedPreferences
SharedPreferences is a simple way to store key-value pairs in Android. It is commonly used for saving application settings and user preferences, as it allows data to persist across user sessions.
Obtaining SharedPreferences
To access SharedPreferences, you need to call one of the following methods in your activity or context:
Example:
The getSharedPreferences
method takes two arguments: the name of the preferences file and the mode (usually Context.MODE_PRIVATE
).
Saving Data to SharedPreferences
To save data, you need to obtain an Editor
object and use its methods to store the values. Finally, call apply()
or commit()
to save the changes.
Example:
editor.putString("username", "JohnDoe");
editor.putInt("user_age", 30);
editor.apply(); // or editor.commit();
The putString
and putInt
methods are used to save a string and an integer, respectively. There are similar methods for other data types like putBoolean
, putFloat
, and putLong
.
Retrieving Data from SharedPreferences
To retrieve data, simply call the appropriate methods on the SharedPreferences object, providing the key and a default value.
Example:
int userAge = sharedPreferences.getInt("user_age", 0);
The getString
and getInt
methods retrieve the stored string and integer values, respectively. If the key does not exist, the default value is returned.
Removing Data from SharedPreferences
To remove a specific key-value pair, use the remove
method on the Editor object. To clear all data, use the clear
method.
Example:
editor.remove("username"); // remove specific key-value pair
editor.clear(); // clear all data
editor.apply(); // or editor.commit();
Conclusion
SharedPreferences is a powerful and simple way to persist data in Android applications. It is well-suited for storing small amounts of data like user settings and preferences. Remember to use the appropriate methods to save, retrieve, and remove data, and always call apply()
or commit()
to ensure your changes are saved.