Shared Preferences
are XML files to store private primitive data in key-value pairs. Data Types include Booleans, floats, ints, longs, and strings.
When we want to save some data which is accessible throughout the application, one way to do is to save it in global variable. But it will vanish once the application is closed. Another and recommended way is to save in SharedPreference
. Data saved in SharedPreferences file is accessible throughout the application and persists even after the application closes or across reboots.
SharedPreferences saves the data in key-value pair and can be accessed in same fashion.
You can create Object of SharedPreferences
using two methods,
1).getSharedPreferences() : Using this methods you can create Multiple SharedPreferences.and its first parameters in name of SharedPreferences
.
2).getPreferences() : Using this method you can create Single SharedPreferences
.
Storing Data
Add a Variable declaration/ Create Preference File
public static final String PREFERENCES_FILE_NAME = "MyAppPreferences";
Retrieve a handle to filename (using getSharedPreferences)
SharedPreferences settingsfile= getSharedPreferences(PREFERENCES_FILE_NAME,0);
Open Editor and Add key-value pairs
SharedPreferences.Editor myeditor = settingsfile.edit();
myeditor.putBoolean("IITAMIYO", true);
myeditor.putFloat("VOLUME", 0.7)
myeditor.putInt("BORDER", 2)
myeditor.putLong("SIZE", 12345678910L)
myeditor.putString("Name", "Amiyo")
myeditor.apply();
Don’t forget to apply/save using myeditor.apply()
as shown above.
Retrieving Data
SharedPreferences mysettings= getSharedPreferences(PREFERENCES_FILE_NAME, 0);
IITAMIYO = mysettings.getBoolean("IITAMIYO", false);
//returns value for the given key.
//second parameter gives the default value if no user preference found
// (set to false in above case)
VOLUME = mysettings.getFloat("VOLUME", 0.5)
//0.5 being the default value if no volume preferences found
// and similarly there are get methods for other data types