Shared Preferences in Android Studio: A Comprehensive Guide
Shared Preferences is a simple way to store key-value pairs of primitive data types in your Android app. It's ideal for storing small amounts of data like user preferences, settings, or temporary data.
How to Use Shared Preferences:
Obtain a SharedPreferences Instance:
Java
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
getSharedPreferences() takes two arguments:
File name: A unique name for the preference file.
Mode: Context.MODE_PRIVATE ensures that only your app can access the file.
2. Edit Shared Preferences:
Java
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "johnDoe");
editor.putInt("age", 30);
editor.putBoolean("isLoggedIn", true);
editor.apply(); // Or editor.commit();
edit() returns an Editor object to modify the preferences.
Use methods like putString(), putInt(), putBoolean(), etc., to add or modify key-value pairs.
apply() or commit() saves the changes. apply() is generally preferred as it's asynchronous and more efficient.
3. Retrieve Values from Shared Preferences:
Java
String username = sharedPreferences.getString("username", "default_username");
int age = sharedPreferences.getInt("age", 0);
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
Use methods like getString(), getInt(), getBoolean(), etc., to retrieve values.
The second argument is a default value to return if the key is not found.
Example: Saving and Retrieving User Preferences
Java
// Save user preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", usernameEditText.getText().toString());
editor.putBoolean("darkModeEnabled",
darkModeSwitch.isChecked());
editor.apply();
// Retrieve user preferences
String savedUsername = sharedPreferences.getString("username", "");
boolean isDarkModeEnabled = sharedPreferences.getBoolean("darkModeEnabled", false);
Key Points to Remember:
Shared Preferences are not suitable for storing large amounts of data or complex data structures.
Data stored in Shared Preferences is not encrypted, so it's not ideal for sensitive information.
Always provide default values for keys to handle cases where the key doesn't exist.
Consider using a more robust solution like SQLite or Room for complex data storage needs.
By following these guidelines, you can effectively use Shared Preferences to store and retrieve simple data in your Android app.