1. Overview
SharedPreferencesclass provides a common framework so that you can save and retrieve permanent key-value pairs for the original data type. You can use it SharedPreferences to save any raw data: Boolean, floating-point, Integer, Long, and string. This data will be persisted across multiple user sessions (even if your app has been terminated).
To get an applied SharedPreferences object, use one of the following two methods:
getSharedPreferences()-Use this method if you need more than one preference file identified by name (specified with the first parameter).
getPreferences()-Use this method if you only need a preference file for Activity. Because this will be the only preference file for Activity, there is no need to provide a name.
Note: Getsharedpreferences () is the context method. Getpreferences () is the activity method.
2. Save Data
the way to save data is simple. is done by the Sharedpreferences.editor class.
Editor Object Acquisition: SharedPreferences provides a method---edit () to get the Sharedpreferences.editor object by invoking the method.
Here are the methods provided by Sharedpreferences.editor:
We can see that the data types supported by Sharedpreferences are: boolean, float, int, long, string, string, type set.
Simple Use Example:
1 sharedpreferences preferences = getsharedpreferences ("Sharedname", mode_private); 2 sharedpreferences.editor Editor = preferences.edit (); 3 editor.putstring ("Key", "abc"); 4 editor.commit ();
Note: The fourth line of code above is very important, without this code, the data is not really saved. In fact, the essence of sharedpreferences data is stored in a fixed format of XML, do not execute the fourth line of code, the data is only in memory, and only the fourth line of code is executed, the data will be saved to the XML, the data can be persisted.
Mode_private: Access to data, which means private, is inaccessible to other applications. There are two other modes, which are not mentioned here.
3. Access to Data
It's also easy to get data. The fetch data is done by the Sharedpreferences class.
The following is a Sharedpreferences class that provides methods for getting data. Very comprehensive, not in detail.
Simple Use Example:
1 sharedpreferences preferences = getsharedpreferences ("Sharedname", mode_private); 2 String text = preferences.getstring ("Key", "");
4. Official address
Official Document Address: Https://developer.android.com/guide/topics/data/data-storage.html#pref
"Android Data Storage" sharedpreferences