SharedPreferences in Android is a great way to store key-value pairs of data. Integrating SharedPreferences with other components, such as Activities, Fragments, or Services, can enhance your app's usability by maintaining user preferences or application state across different sessions.
In this example, we will see how to save and retrieve user preferences using SharedPreferences within an Activity.
// Saving data to SharedPreferences in an Activity
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "JohnDoe");
editor.putBoolean("isLoggedIn", true);
editor.apply();
// Retrieving data from SharedPreferences in an Activity
SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "defaultUser");
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
Using SharedPreferences in a Fragment is similar and allows you to maintain consistency in user data.
// Inside a Fragment
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("MyPrefs", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "defaultUser");
// Update UI or perform action based on the value retrieved
if (username.equals("JohnDoe")) {
// Do something
}
SharedPreferences can also be accessed in a Service, allowing you to continuously check user preferences or settings even when the app is not in the foreground.
// Inside a Service
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("MyPrefs", MODE_PRIVATE);
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
if (isLoggedIn) {
// Service actions if logged in
}
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?