Ⅰ. Introduction
Most of the time we develop software needs to provide users with software parameter setting functions , such as our common QQ, users can set whether to allow strangers to add themselves as friends. For the preservation of software configuration parameters, if the window software is usually used to save the INI file, if it is a J2SE application, we will use the Properties attribute file or XML to save. If it's an Android app, what's the best way to save software configuration parameters? The Android platform provides us with a sharedpreferences class, which is a lightweight storage class that is especially suitable for saving software configuration parameters. Sharedpreferences is similar to the previous INI configuration file on Windows systems, but it is divided into multiple permissions, can be shared globally, and ultimately stored in XML, overall efficiency is not particularly high, for the general lightweight is much better than SQLite, If you do not have a real storage capacity, consider your own definition file format. XML processing is Dalvik through the native XML parser, such as the Xmlpull method, which is better for memory resource consumption.
Use Sharedpreferences to save the data, behind it is the XML file to hold the data, the file is stored in the/data/data/<package name>/shared_prefs directory (requires the user's root permission)
The sharedpreferences is simple to use and can easily store data and read data. 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. This should be the simplest way for Android to read and write external data. His usage is basically the same as in J2SE (Java.util.prefs.Preferences), in a simple, transparent way to save some user personalization font, color, location, and other parameter information. General applications provide such interfaces as "settings" or "preferences", which can then be saved through preferences, and the programmer does not need to know exactly what form it is saved in and where it is stored. Of course, if you are willing to save something else, there is no limit. I just don't know what the problem is with performance.
Ⅱ. Using
The steps to save the Key-value pair using Sharedpreferences are as follows:
(1) Use the Getsharedpreferences method of the activity class to get the Sharedpreferences object, where the name of the file that stores the Key-value is specified by the first parameter of the Getsharedpreferences method.
(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.
The writing process for the specific code is:
A, storage data information
1. Open preferences, name is setting, if present, open it, otherwise create a new preferencessharedpreferences settings = getsharedpreferences ("Setting ", 0);//2, let setting in the editing state sharedpreferences.editor editor = Settings.edit ();//3, storing Data editor.putstring (" name "," Ataaw ") ; Editor.putstring ("URL", "ataaw.com"),//4, complete submission editor.commit ();
Because Sharedpreferences is behind the use of XML files to save data, the first parameter of the Getsharedpreferences (Name,mode) method is used to specify the name of the file, without a suffix, and the suffix is automatically added by Android. The second parameter of the method specifies the mode of operation of the file, with a total of four modes of operation.
- activity.mode_private,//default mode of operation, on behalf of the file is private data, can only be accessed by the application itself, in this mode, the content will overwrite the contents of the original file, if you want to append the newly written content to the original file, you can use Activity.mode_ APPEND
- activity.mode_world_readable,//indicates that the current file can be read by another application.
- activity.mode_world_writeable,//indicates that the current file can be written by another application;
If you want the file to be read and written by another app, you can pass in: activity.mode_world_readable+activity.mode_world_writeable
- activity.mode_append//This mode checks whether a file exists, appends content to the file, or creates a new file
If you want the XML file behind sharedpreferences to be read and written by other applications, you can specify context.mode_world_readable and context.mode_world_writeable permissions.
In addition, the activity also provides another getpreferences (mode) method operation Sharedpreferences, which defaults to the name of the file using the current class without the package name.
B, read the data information
1. Get preferencessharedpreferences settings = getsharedpreferences ("setting", 0);//2, remove data string name = Settings.getstring ("name", "Default value"),//getstring () the second parameter is the default value, and if the key does not exist in preference, the default value of string URL = setting.getstring is returned. ("URL", "Default");
This is how sharedpreferences is used in Android, where the preferences file location you create can be viewed in eclipse:
Ddms->file Explorer/<package Name>/shared_prefs/setting.xml
Operating mechanism context internal implementation
The Getsharedpreferences () method itself is an abstract method defined in the context of this interface, which is implemented by the Contextimpl class.
1, call Getsharedpreferences () to obtain the corresponding file, the function implementation functions as follows:
The context class static data collection, which holds all data collections formed after reading the XML file with key-value pairs private static final Hashmap<file, sharedpreferencesimpl> Ssharedprefs = new Hashmap<file, sharedpreferencesimpl> (); @Overridepublic sharedpreferences getsharedpreferences (String name, int mode) {//its corresponding Sharedpreferencesimpl object, The object has a HashMap collection that holds our serialization results for that file Sharedpreferencesimpl sp; File f = getsharedprefsfile (name); If there is a corresponding file under the package, there is no new synchronized (ssharedprefs) {//has read the file, it is returned directly to the Sharedpreferences object sp = Sshar Edprefs.get (f); if (sp! = null &&!sp.hasfilechanged ()) {//log.i (TAG, "returning existing prefs" + name + ":" + sp) ; return SP; }}//The following is a serialization of the XML file, while writing data to the map collection in map map = null; if (f.exists () && f.canread ()) {try {str = new FileInputStream (f); Map = Xmlutils.readmapxml (str); Str.close (); } ... } Synchronized (ssharedprefs) {if (sp! =NULL) {//LOG.I (TAG, "Updating existing prefs" + name + "" + SP + ":" + map); Sp.replace (map); Update data Collection} else {sp = Ssharedprefs.get (f); if (sp = = null) {//Creates a new Sharedpreferencesimpl object and sets its related properties sp = new Sharedpreferencesimpl (f, mode, map); Ssharedprefs.put (f, SP); }} return SP; }}
2, Sharedpreferences is just an interface, it defines a number of methods to manipulate XML files, the real implementation of the class is Sharedpreferencesimpl, the class is the inner class of CONTEXTIML, the class is as follows:
In this form, we contacted//sharedpreferences when we analyzed the context contextiml is just an interface, and its real implementation class is the Sharedpreferencesimpl class private static final class Sharedpreferencesimpl implements Sharedpreferences{private Map MMap; Save the file serialization result of the operation, the key value pair form//through the key value to obtain the corresponding value value public string getString (string key, String defvalue) { synchronized ( This) { string v = (string) mmap.get (key); Return v! = null? V:defvalue; }
Reference:
http://blog.csdn.net/wxyyxc1992/article/details/17222841
"Doing the project while learning Android" Knowledge Point: Sharedpreferences