android shared preferences

Android Shared Preferences is a way for applications to store small amounts of data in key-value pairs. This data is stored in a private file in the application's data directory and can be accessed and modified only by the application.

Shared Preferences are commonly used to store application settings, user preferences, and other data that needs to persist across application launches. Here's how to use Shared Preferences in an Android application:

  1. Create a Shared Preferences instance: To create a new Shared Preferences instance, call the getSharedPreferences() method and pass in a name for the preferences file and a mode.

  2. Write data to Shared Preferences: To write data to Shared Preferences, call the edit() method on the Shared Preferences instance to get an Editor object. Use the Editor object to add key-value pairs to the preferences file using the putString(), putInt(), putBoolean(), or other similar methods.

  3. Commit the changes: After making changes to the preferences file, you must call the commit() method on the Editor object to save the changes to disk.

  4. Read data from Shared Preferences: To read data from Shared Preferences, call the appropriate getter method on the Shared Preferences instance, such as getString(), getInt(), or getBoolean(), and pass in the key for the value you want to retrieve.

  5. Update data in Shared Preferences: To update data in Shared Preferences, simply call the put method with the new value and call commit() to save the changes.

Here's an example of how to use Shared Preferences to store and retrieve a user's name:

refer t‮tfigi:o‬idea.com
// Create a new Shared Preferences instance
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);

// Write the user's name to Shared Preferences
SharedPreferences.Editor editor = prefs.edit();
editor.putString("UserName", "John Doe");
editor.commit();

// Read the user's name from Shared Preferences
String userName = prefs.getString("UserName", "");