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:
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.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 theputString()
,putInt()
,putBoolean()
, or other similar methods.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.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()
, orgetBoolean()
, and pass in the key for the value you want to retrieve.Update data in Shared Preferences: To update data in Shared Preferences, simply call the
put
method with the new value and callcommit()
to save the changes.
Here's an example of how to use Shared Preferences to store and retrieve a user's name:
refer ttfigi:oidea.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", "");