Sharedpreferences is a lightweight data storage method that stores Key-value pairs key-value pairs of data based on XML files and is typically used to store some simple configuration information. The Sharedpreferences object itself can only fetch data without supporting storage and modification, and storage modifications are implemented through the editor object. Each sharedpreferences file is managed by the framework and can be private or shareable.
Data storage
To create a new Android project, in the OnCreate method of mainactivity, call the Getsharedpreferences method, notice that if the file already exists, it will not be created, and if the key value pair does not exist, it will continue to be added to it. If the name is the same, the value will overwrite the original value.
Context Context=mainactivity.this; Sharedpreferences shared=context.getsharedpreferences ("Test", mode_private); Editor Editor=shared.edit (); Editor.putstring ("Name", "flyelephant"); Editor.putint ("Age",); Editor.putboolean ("Ismarried", false); Editor.commit ();
After the storage after this time found that the folder more than a test.xml, the full path should be data/data/com.example.preference/shared_prefs/test.xml
After exporting, the contents of the XML are found as:
<?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '? ><map><string name= "Name" >flyelephant</ String><int name= "Age" value= "/><boolean name=" Ismarried "value=" false "/></map>
Show Data
Set a button click event loaddata
public void LoadData (view view) { sharedpreferences shared=mainactivity.this.getsharedpreferences ("Test", Mode_ PRIVATE); EditText edittext= (EditText) Findviewbyid (r.id.edit_sharedname); Edittext.settext (shared.getstring ("Name", "" ")); EditText editage= (EditText) Findviewbyid (r.id.edit_sharedage); String agestring=string.valueof (Shared.getint ("age", 0)); Editage.settext (agestring); }
Data Display results:
Delete a node
Click the second button to perform the event:
public void Deletenode (view view) { sharedpreferences shared=mainactivity.this.getsharedpreferences ("Test", MODE _private); Editor Editor=shared.edit (); Editor.remove ("Age"); Editor.commit (); Toast.maketext (mainactivity.this, "delete succeeded", Toast.length_short). Show ();
The effect is as follows:
Deleting Files
Depending on the path, a file is called directly to delete it:
public void DeleteFile (view view) { String pathstring= "/data/data/" +getpackagename () + "/shared_prefs"; File File=new file (pathstring, "Test.xml"); LOG.I ("Com.example.preference", pathstring); if (file.exists ()) {File.delete ();} Toast.maketext (mainactivity.this, "File deletion succeeded", Toast.length_short). Show ();
Android Beginner, daytime company engage in. NET, come back to do Android in the evening, feel back to the university, feel very good ~
Sharedpreferences of Android Data storage