First, we will introduce the role of the sharedpreferences interface:
We all know that many times we always put some system-dependent parameter settings in a configuration file. For example, we usually use * in Java *. properties file. In Android, we also have a file similar *. properties, and the object representation of such files in Android is sharedpreferences. You can think that the sharedpreferences used in each application is a ing of the application file.
Now we know that the sharedpreferences interface allows us to store some values.
In the sharedpreferences API description, we can see this introduction.
Interface for accessing and modifying preference data returned by getsharedpreferences (string, INT ). for any special set of preferences, there is a single instance of this class that all clients share. modifications to the preferences must go through an sharedpreferences. editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. </P> <p> Note: currently this class does not support use of your SS multiple processes. this will be added later. </P> <p>
Translation:
The sharedpreferences interface is generally used to access or modify the settings returned by the getsharedpreferences (string, INT) method. The configuration information here is unique for a single instance, which means that the configuration information will be shared by the client (mobile phone) installed with the APK application. To modify these settings, you must use sharedpreferences. the editor object can be modified only after obtaining the editor object. The reason is that, as we have mentioned earlier, the configuration change information will be shared by all clients, this means that several clients may need to modify the values in the configuration information at the same time, which is prone to confusion in data modification. Here we get sharedpreferences. the editor object is designed to ensure data consistency. Note: up to now, sharedpreferences does not support multi-process processing and is in the pending status.
Let's take a look at the main methods in this interface:
Sharedpreferences contains two internal classes: sharedpreferences. editor and sharedpreferences. onsharedpreferenceschangelistener; the editor is mainly used to modify the attribute settings, while the onsharedpreferenceschangelistener is an event triggered when the attribute is modified. We can perform some additional actions in it, for example, some page changes are triggered based on new property values, and so on ......
As for other methods, it is very simple. I will not go into details when I look at the method name. Here is an example of an application:
First:
Then main. xml
<? XML version = "1.0" encoding = "UTF-8"?> <Br/> <linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" <br/> Android: Orientation = "vertical" <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "fill_parent" <br/> <textview <br/> Android: layout_width = "fill_parent" <br/> Android: layout_height = "wrap_content" <br/> Android: id = "@ + ID/textview" <br/> </linearlayout> <br/>
Activity Code:
Package cn.com. sharedpreferencestest; </P> <p> Import android. app. activity; <br/> Import android. content. sharedpreferences; <br/> Import android. OS. bundle; <br/> Import android. util. log; <br/> Import android. widget. textview; </P> <p> public class sharedpreferencesactivity extends activity {<br/> @ override <br/> Public void oncreate (bundle savedinstancestate) {<br/> super. oncreate (savedinstancestate); <br/> Setcontentview (R. layout. main); <br/> savesharedpreferences (); <br/> readsharedpreferences (); </P> <p >}</P> <p>/** <br/> * @ author chenzheng_java <br/> * @ Description: Create and save some Settings <br/> * @ since 2011/03/05 <br/> */<br/> private void savesharedpreferences () {<br/>/* <br/> * The getsharedpreferences (string name, int mode) method is an abstract method defined in context. It is implemented in contextwrapper, <br/> * This method creates a sharedpre Based on the name and write type passed by the user. The ferences object is returned. <Br/> * in activity, you can return to the sharedpreferences object by using sharedpreferences = getpreferences (mode_private ); <br/> * define and implement the modification method in the activity, there is no name parameter here because this method uses the Class Name of the current activity as the name attribute by default (the class name here does not contain the package path) <br/> **/<br/> sharedpreferences = getsharedpreferences ("Preferences", mode_private); </P> <p> // store data <br/> sharedpreferences. editor editor = sharedpreferences. edit (); <br/> ed Itor. putstring ("name", "Cai Yilin"); <br/> editor. putint ("Age", 31); <br/> Boolean B = editor. commit (); </P> <p> If (B) {<br/> log. I ("Notification:", "saved successfully! "); <Br/>}else {<br/> log. I (" notification "," failed to save! "); <Br/>}</P> <p>/** <br/> * @ author chenzheng_java <br/> * @ description data added to the sharedpreference object <br/> * @ since 2011/03/05 <br/> */<br/> private void readsharedpreferences () {<br/> string result = "Beauty info:/N"; <br/> sharedpreferences = This. getsharedpreferences ("Preferences", mode_private); <br/> result + = "name" + sharedpreferences. getstring ("name", "No person now"); <br/> result + = "Age" + sharedpreferences. getint ("Age",-1); <br/> textview = (textview) findviewbyid (R. id. textview); <br/> textview. settext (result); </P> <p >}</P> <p>}
Others are default.
---------------------------------------------------------------------
Finally, let's talk nonsense.
Sharedpreferences stores data in key-value pairs. If the same key is set twice, the later value will overwrite the previous value. In fact, sharedpreferences stores data in the background in the format of an XML file. The stored directory is/data/application package name/shared_prefs.
For example:
<? XML version = '1. 0' encoding = 'utf-8' standalone = 'Yes'?> <Br/> <map> <br/> <int name = "Age" value = "31"/> <br/> <string name = "name"> Cai Yilin </ string> <br/> </map> <br/>
In addition, sharedpreferences objects have strict requirements on the format of stored values. We can see from the method that only data of the string/INT/long/float/Boolean types can be stored.
Bytes ------------------------------------------------------------------------------------
TIPS: if we want to access the sharedpreferences object of another activity (such as cn.com. ABC. activitytest) in the current activity, how can we get it?
Obtain the following information:
// Obtain cn.com. ABC. the context object of activitytest, which is obtained through the context object. Note that the mode must be context. mode_world_readable </P> <p> context otherappcontext = createpackagecontext ("cn.com. ABC. activitytest ", context. context_ignore_security); </P> <p> sharedpreferences = otherappcontext. getsharedpreferences ("Preferences", context. mode_world_readable); </P> <p>
--------------------------------------------------------------
Finally, paste the source code of sharedpreferences for your convenience.
/* <Br/> * copyright (c) 2006 the android open source project <br/> * licensed under the Apache license, version 2.0 (the "License"); <br/> * you may not use this file except T in compliance with the license. <br/> * You may obtain a copy of the license at <br/> * http://www.apache.org/licenses/LICENSE-2.0 <br/> * unless required by applicable law or agreed to in writing, soft Ware <br/> * distributed under the license is distributed on an "as is" basis, <br/> * Without warranties or conditions of any kind, either express or implied. <br/> * See the license for the specific language governing permissions and <br/> * limitations under the license. <br/> */</P> <p> package android. content; </P> <p> Import Java. util. map; </P> <p>/** <br/> * interface for accessing and modifying P Reference data returned by {@ link <br/> * context # getsharedpreferences }. for any particle set of preferences, <br/> * There is a single instance of this class that all clients share. <br/> * modifications to the preferences must go through an {@ link editor} object <br/> * To ensure the preference values remain in a consistent state and Control <br/> * when they are committed to storage. <br/> * <Br/> * <p> <em> Note: currently this class does not support use internal SS multiple <br/> * processes. this will be added later. </em> <br/> * @ SEE context # getsharedpreferences <br/> */<br/> Public interface sharedpreferences {<br/> /** <br/> * interface definition for a callback to be invoked when a shared <br/> * preference is changed. <br/> */<br/> Public interface onsharedpreferencechangel Istener {<br/>/** <br/> * called when a shared preference is changed, added, or removed. this <br/> * may be called even if a preference is set to its existing value. <br/> * @ Param sharedpreferences the {@ link sharedpreferences} that received ed <br/> * the change. <br/> * @ Param key the key of the preference that was changed, added, or <br/> * removed. <br/> */<br/> void onsharedpreferen Cechanged (sharedpreferences, string key ); <br/>}</P> <p>/** <br/> * interface used for modifying values in a {@ link sharedpreferences} <br/> * object. all changes you make in an editor are batched, and not copied <br/> * back to the original {@ link sharedpreferences} or persistent storage <br/> * until you call {@ link # commit }. <br/> */<br/> Public interface editor {<br/>/** <Br/> * set a string value in the preferences Editor, to be written back once <br/> * {@ link # commit} is called. <br/> * @ Param key the name of the preference to modify. <br/> * @ Param value the new value for the preference. <br/> * @ return returns a reference to the same editor object, so you can <br/> * chain put calltogether. <br/> */<br/> editor putstring (string key, string Value); </P> <p>/** <br/> * set an int value in the preferences editor, to be written back once <br/> * {@ link # commit} is called. <br/> * @ Param key the name of the preference to modify. <br/> * @ Param value the new value for the preference. <br/> * @ return returns a reference to the same editor object, so you can <br/> * chain put calltogether. <br/> */<br/> editor putint (strin G key, int value); </P> <p>/** <br/> * set a long value in the preferences editor, to be written back once <br/> * {@ link # commit} is called. <br/> * @ Param key the name of the preference to modify. <br/> * @ Param value the new value for the preference. <br/> * @ return returns a reference to the same editor object, so you can <br/> * chain put calltogether. <br/> */<br/> editor P Utlong (string key, long value); </P> <p>/** <br/> * set a float value in the preferences editor, to be written back once <br/> * {@ link # commit} is called. <br/> * @ Param key the name of the preference to modify. <br/> * @ Param value the new value for the preference. <br/> * @ return returns a reference to the same editor object, so you can <br/> * chain put calltogether. <br/> */< Br/> editor putfloat (string key, float value); </P> <p>/** <br/> * set a Boolean value in the preferences editor, to be written back <br/> * once {@ link # commit} is called. <br/> * @ Param key the name of the preference to modify. <br/> * @ Param value the new value for the preference. <br/> * @ return returns a reference to the same editor object, so you can <br/> * chain put callt Ogether. <br/> */<br/> editor putboolean (string key, Boolean value ); </P> <p>/** <br/> * mark in the editor that a preference value shoshould be removed, which <br/> * will be done in the actual preferences once {@ link # commit} is <br/> * called. <br/> * <p> note that when committing back to the preferences, all removals <br/> * are done first, regardless of whether you called remove before <br /> * Or after put methods on this editor. <br/> * @ Param key the name of the preference to remove. <br/> * @ return returns a reference to the same editor object, so you can <br/> * chain put calltogether. <br/> */<br/> editor remove (string key ); </P> <p>/** <br/> * mark in the editor to remove <em> all </em> values from the <br/> * preferences. once commit is called, The only Rema Ining preferences <br/> * will be any that you have defined in this editor. <br/> * <p> note that when committing back to the preferences, the clear <br/> * is done first, regardless of whether you called clear before <br/> * or after put methods on this editor. <br/> * @ return returns a reference to the same editor object, so you can <br/> * chain put calltogether. <br/> */<br/> Editor clear (); </P> <p>/** <br/> * commit your preferences changes back from this editor to the <br/> * {@ link sharedpreferences} object it is editing. this atomically <br/> * performs the requested modifications, replacing whatever is currently <br/> * in the sharedpreferences. <br/> * <p> note that when two editors are modifying preferences at the same <br/> * time, the last one to call Commit wins. <br/> * @ return returns true if the new values were successfully written <br/> * to persistent storage. <br/> */<br/> Boolean commit (); <br/>}</P> <p>/** <br/> * retrieve all values from the preferences. <br/> * @ return returns a map containing a list of pairs key/value representing <br/> * the preferences. <br/> * @ throws nullpointerexception <br/> */<br/> Map <string,?> Getall (); </P> <p>/** <br/> * retrieve a string value from the preferences. <br/> * @ Param key the name of the preference to retrieve. <br/> * @ Param defvalue value to return if this preference does not exist. <br/> * @ return returns the preference value if it exists, or defvalue. throws <br/> * classcastexception if there is a preference with this name that is not <br/> * a string. <br/> * @ throws classcastexception <br/> */<br/> string getstring (string key, string defvalue ); </P> <p>/** <br/> * retrieve an int value from the preferences. <br/> * @ Param key the name of the preference to retrieve. <br/> * @ Param defvalue value to return if this preference does not exist. <br/> * @ return returns the preference value if it exists, or defvalue. throws <br/> * classcastexception if there is a preference with this name that is not <br/> * an int. <br/> * @ throws classcastexception <br/> */<br/> int getint (string key, int defvalue ); </P> <p>/** <br/> * retrieve a long value from the preferences. <br/> * @ Param key the name of the preference to retrieve. <br/> * @ Param defvalue value to return if this preference does not exist. <br/> * @ return returns the preference value if it exists, or defvalue. throws <br/> * classcastexception if there is a preference with this name that is not <br/> * a long. <br/> * @ throws classcastexception <br/> */<br/> long getlong (string key, long defvalue ); </P> <p>/** <br/> * retrieve a float value from the preferences. <br/> * @ Param key the name of the preference to retrieve. <br/> * @ Param defvalue value to return if this preference does not exist. <br/> * @ return returns the preference value if it exists, or defvalue. throws <br/> * classcastexception if there is a preference with this name that is not <br/> * a float. <br/> * @ throws classcastexception <br/> */<br/> float getfloat (string key, float defvalue ); </P> <p>/** <br/> * retrieve a Boolean value from the preferences. <br/> * @ Param key the name of the preference to retrieve. <br/> * @ Param defvalue value to return if this preference does not exist. <br/> * @ return returns the preference value if it exists, or defvalue. throws <br/> * classcastexception if there is a preference with this name that is not <br/> * A boolean. <br/> * @ throws classcastexception <br/> */<br/> Boolean getboolean (string key, Boolean defvalue ); </P> <p>/** <br/> * checks whether the preferences contains a preference. <br/> * @ Param key the name of the preference to check. <br/> * @ return returns true if the preference exists in the preferences, <br/> * Otherwise false. <br/> */<br/> Boolean contains (string key); </P> <p>/** <br/> * Create a new editor for these preferences, through which you can make <br/> * modifications to the data in the preferences and atomically commit those <br/> * changes back to the sharedpreferences object. <br/> * <p> note that you <em> must </em> call {@ link editor # commit} to have any <br/> * changes you perform in the editor actually show up in the <br/> * sharedpreferences. <br/> * @ return returns a new instance of the {@ link editor} interface, allowing <br/> * you to modify the values in this sharedpreferences object. <br/> */<br/> editor edit (); </P> <p>/** <br/> * registers a callback to be invoked when a change happens to a preference. <br/> * @ Param listener the callback that will run. <br/> * @ see # unregisteronsharedpreferencechangelistener <br/> */<br/> void registeronsharedpreferencechangelistener (onsharedpreferencechangelistener listener ); </P> <p>/** <br/> * unregisters a previous callback. <br/> * @ Param listener the callback that shoshould be unregistered. <br/> * @ see # registeronsharedpreferencechangelistener <br/> */<br/> void listener (onsharedpreferencechangelistener listener); <br/>}< br/>