First, sharedpreferences
1 Storage of data using Sharedpreference
many times we develop software to provide users with software parameter setting functions, such as our commonQQ, users can set whether strangers are allowed to add themselves as friends. For the saving of software configuration parameters, if it iswindowsoftware usually we useINIfile to be saved, if yesJ2SEapplication, we will adoptPropertiesProperties file orXMLto save. If it isAndroidapplication, what is the best way to save software configuration parameters? Androidthe platform provides us with asharedpreferencesclass, which is a lightweight storage class that is especially suitable for saving software configuration parameters. UsesharedpreferencesSave the data, behind it withXMLThe file holds the data and the file is stored in/data/data/<packagename>/Shared_prefsDirectory:
sharedpreferences sharedpreferences = getsharedpreferences ("itcast",context.mode_private);
Editor Editor = Sharedpreferences.edit ();// Get editor
editor.putstring ("name", "Andy");
Editor.putint ("Age", 4);
Editor.commit ();// Submit Changes
generated by Andy . XML The contents of the file are as follows:
<?xmlversion= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '?>
<map>
<stringname= "name" > Andy </string>
< int name= "Age" value= "4"/>
</map>
because sharedpreferences behind is the use of the xml file save data, getsharedpreferences ( name,mode android Auto Plus. The second parameter of the method specifies the mode of operation of the file, there are four modes of operation, which are described in the previous four modes of saving data using file mode. If you want sharedpreferences xml files can be read and written by other applications, you can specify and context.mode_ world_writeable permissions.
also Activity also provides another getpreferences (Mode) Method Action sharedpreferences , this method defaults to the name of the file using the current class without the package name.
2 reading with sharedpreferences data
Access sharedpreferences the data in the code is as follows:
sharedpreferences sharedpreferences = getsharedpreferences ("Andy",context.mode_private); Set file types ask this app to access
// getString () The second parameter is the default value, and if the key does not exist in preference , the default value is returned
Stringname = sharedpreferences.getstring ("name", "");
int Age = Sharedpreferences.getint ("Age", 1);
If you visit an app in another Preference, The precondition is: the Preference when created, specifies the context.mode_world_readable or context.mode_world_writeable permissions. For example, a <packagename> for cn.itcast.action uses the following statement to create a Preference
getsharedpreferences ("itcast",Context. ) mode_world_readable );
other applications to access the above applied Preference, first, you need to create the above applied Context , and then through Context Access Preference , Access Preference in the app's package. Shared_prefs Directory found Preference :
Context Otherappscontext = Createpackagecontext ("cn.andy.action",Context. ) context_ignore_security );
sharedpreferences sharedpreferences = otherappscontext.getsharedpreferences ("Andy",context.mode_world_readable);
Stringname = sharedpreferences.getstring ("name", "");
int Age = Sharedpreferences.getint ("Age", 0);
If you do not create a Context access to other apps Preference , or you can read the XML Direct access to other applications using file mode Preference corresponding to the XML files, such as:
File xmlfile =new File ("/data/data/<package name>/shared_prefs/andy.xml");//<packagename > should be replaced with the app's package name
3 detailed code is as follows:
1 Save sharedpreferences in mainactivity
Package Com.andy.sharedpreference;import Java.util.map;import Com.andy.sharedpreference.r;import Com.andy.service.preferenceservice;import Android.support.v7.app.actionbaractivity;import Android.os.Bundle; Import Android.view.menu;import android.view.menuitem;import android.view.view;import android.widget.EditText; Import Android.widget.toast;public class Mainactivity extends Actionbaractivity {private EditText nametext;private EditText agetext;private preferenceservice preferenceservice; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); NameText = ( EditText) Findviewbyid (r.id.name) Agetext = (EditText) Findviewbyid (r.id.age);p referenceservice = new Preferenceservice (this); map<string, string> params = Preferenceservice.getsharedperence (); Nametext.settext (Params.get ("name")); Agetext.settext (Params.get ("Age")); }//corresponds to Android:onclick method public void Save (view view) {String name = Nametext.gettext (). toStRing (); String age = Agetext.gettext (). toString ();p referenceservice.savesharedpreference (name, integer.valueof (age));// Toast Be sure to call show to show Toast.maketext (Getapplicationcontext (), r.string.success, Toast.length_short). Show (); @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar will//automatically handle clicks on the Home/up button so long//as you specify a parent activity in and RoidManifest.xml.int id = item.getitemid (); if (id = = r.id.action_settings) {return true;} return super.onoptionsitemselected (item);}}
2 Preferenceservice for Read and save
Package Com.andy.service;import Java.util.hashmap;import Java.util.map;import android.content.context;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;import Android.util.Log;public Class Preferenceservice {private static final String TAG = "Preferenceservice";p rivate Context context;public PreferenceS Ervice (Context context) {super (); this.context = context;} /** * Save Sharedperence * * @param name * @param age */public void Savesharedpreference (String name, Integer age) {LOG.I (TA G, "set sharedpreference");//Sharedpreference Save file is an XML type and the suffix system automatically adds sharedpreferences sharedpreferences = Context.getsharedpreferences ("Andy", context.mode_private);//Get editor Edit editors = Sharedpreferences.edit (); Editor.putstring ("name", name); Editor.putint ("Age", age); Editor.commit (); Must be Commit}public map<string, string> getsharedperence () {log.i (TAG, "Get Sharedpreference"); Sharedpreferences sharedpreferences = context.getsharedpreferences ("Andy", Context.mode_private); map<string, string> params = new hashmap<string, string> ();p arams.put ("name", sharedpreferences.getstring ("Name", "")); Params.put ("Age", String.valueof (The Sharedpreferences.getint ("age", 0)); return params;}}
The Sharedpreferences of Android development