Before the application encountered such a problem: in the "A" activity to and "B" activity fragment communication value, but suddenly found unable to get B fragment handler, and can not send broadcast, After a brief thought of sharedpreferences, this lightweight data storage method.
The essence of sharedpreferences is to store key-value key-value pairs of data based on XML files, usually to store some simple configuration information, it is not cost-effective to store with SQLite database, because the database connection and operation time greatly affect the efficiency of the program. Its storage location is under the/data/data/< package name >/shared_prefs directory.
In addition, Sharedpreferences can save only simple types of data, such as String, int, and so on. It is common to convert data of complex types to Base64 encoding, then save the converted data as a string in an XML file, and then save it with Sharedpreferences.
The steps to save the Key-value pair using Sharedpreferences are as follows:
(1) The Getsharedpreferences method of the activity class is used to obtain the Sharedpreferences object, where the name of the file that stores the Key-value is specified by the first parameter of the Getsharedpreferences method. The second parameter specifies permissions to access the application's private files.
(2) Use edit of Sharedpreferences interface to get Sharedpreferences.editor object.
(3) The Putxxx method of Sharedpreferences.editor interface is used to save the key-value pair. where xxx represents a different data type. For example, the value of string type requires the Putstring method.
(4) The Key-value pair is saved by the commit method of the Sharedpreferences.editor interface. The Commit method is equivalent to a commit operation in a database transaction.
To store data information, proceed as follows:
A, open preferences, name is setting, open it if it exists, or create a new preferences
Sharedpreferences usersettings = getsharedpreferences ("setting", 0);
b, let setting in the editing state
Sharedpreferences.editor Editor = Usersettings.edit ();
C, Storage data
Editor.putstring ("name", "Ataaw");
Editor.putstring ("URL", "ataaw.com");
D, complete the submission
Editor.commit ();
Read Data information, the steps are as follows:
A, get preferences
Sharedpreferences usersettings= getsharedpreferences ("setting", 0);
b, take out the data
String name = usersettings.getstring ("name", "Default value");
String url = usersettings.getstring ("url", "Default");
The above is the specific use of sharedpreferences in Android.
Note: Just talk about the access method, add a little ha, that is, delete and empty operations, as follows:
A. Clear the specified data
Sharedpreferences.editor Editor = Usersettings.edit ();
Editor.remove ("KEY");
Editor.commit ();
B. Clear the data
Sharedpreferences.editor Editor = Usersettings.edit ();
Editor.clear ();
Editor.commit ();
< finish >