What is SharedPreferences in Android SDK?

SharedPreferences in Android SDK is a lightweight, key-value pair storage mechanism. It allows developers to store small amounts of data in the form of primitive types such as boolean, float, int, long, and String. It's commonly used for saving user preferences or application settings.

SharedPreferences provides a simple API to fetch and update data. It is persistent, meaning the data will remain across sessions. This makes it ideal for storing user preferences, app settings, or other small bits of information that need to be preserved.

Here is a simple example of how to use SharedPreferences in Android:

// Save data to SharedPreferences SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("username", "JohnDoe"); editor.putBoolean("isLoggedIn", true); editor.apply(); // or editor.commit(); // Retrieve data from SharedPreferences String username = sharedPreferences.getString("username", "defaultUser"); boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);

SharedPreferences Android SDK key-value storage user preferences app settings persistent storage