Android provides a lightweight data persistence method. Use the Sharedpreferences interface to store primitive data in key-value form in a file. Many are used to save software preference configuration information.
Note the points:
1. Storage content: Primitive data. (Booleans, floats, ints, longs, and strings.)
2. Storage form: Key-value Key-value pairs, stored in an XML file.
The method used:
Getsharedpreferences (String name, int mode) "or getpreferences ()" Obtains the Sharedpreferences object.
Read operation:
Getboolean getInt, and so on, are obtained by calling the Sharedpreferences object directly.
Write operation:
The editor object is obtained by sharedpreferences, which adapts to the editor object to call Putboolean and write the file.
Sharedpreferences file storage address:/data/data/<packagename>/shared_prefs Directory
Example: Remember password function of user login interface
public class Mainactivity extends Activity {EditText user_name, Pass_word; CheckBox Remembercheck; Button btnlogin;//sharedpreferences setting, @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); user_name = (EditText) findViewById ( R.id.etusername);p Ass_word = (EditText) Findviewbyid (r.id.etpassword); Remembercheck = (CheckBox) Findviewbyid ( R.ID.CHECKBOX1); btnlogin = (Button) Findviewbyid (r.id.btnlogin);//Read sharedpreference value sharedpreferences sharepre = Getsharedpreferences ("Data", mode_private); If the data file does not exist, create a//string ischeckedstr = sharepre.getstring ("isChecked", "" "); Boolean isChecked = Sharepre.getboolean ("isChecked", false); if (isChecked) {String username = sharepre.getstring ("username", "") with default values; String Password = sharepre.getstring ("Password", "" "), User_name.settext (username);p ass_word.settext (password); Remembercheck.setchecked (TRUE);} Login Event Response Btnlogin.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method Stubsharedpreferences.editor Editor = GETSHAREDPR Eferences ("Data", Mode_private). Edit (); if (remembercheck.ischecked ()) {//Save value to Sharedpreferenceseditor.putboolean (" IsChecked ", true); Editor.putstring (" username ", User_name.gettext (). toString ()); Editor.putstring (" Password ", Pass_ Word.gettext (). toString ());} Else{editor.clear ();} Editor.commit (); Intent i = new Intent (mainactivity.this,settingactivity.class); startactivity (i);}});}
The resulting XML file can be found in the file explorer of DDMS:
Android sharedpreferences Usage