How to integrate SharedPreferences with other Android components?

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.

Example of Integrating SharedPreferences with Activities

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);

Integrating SharedPreferences with Fragments

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 }

Using SharedPreferences in Services

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 }

SharedPreferences Android Activities Fragments Services user preferences Android components