How to Use SharedPreference to save files for Android storage Learning
In the last two sections, we used text files to store user information, which is obviously vulnerable. At the same time, it is difficult to manage the content in the file. Today, we learn to use SharedPreference to save. SharedPreference stores scattered data.
We still use the example in the section to analyze and save the user information using SharedPreference.
Note: If you do not know the example, read and write files in the internal storage of Android storage.
Click OK to save the user information:
Public void login (View v) {String name = ed_nam.getText (). toString (); String passwd = ed_passwd.getText (). toString (); // determines whether the user name or password is input if (name. equals () | (passwd. equals () {Toast. makeText (this, the user name or password cannot be blank, Toast. LENGTH_SHORT ). show ();} else {if (cb. isChecked () {// use sharedPreference to save user information. // The default path of SharedPreference is/cmd_prefs/SharedPreferences sp = getSharedPreferences (info, MODE_PRIVATE); // get the Editor editor Editor = sp. edit (); editor. putString (name, name); editor. putString (passwd, passwd); // submit the editor. commit ();} Toast. makeText (this, logon successful, Toast. LENGTH_SHORT ). show ();}}
You can see that there is an info file in the sharedPreference path.
Export. Info. xml is saved as key and value
1233333 Ert
When you come in again, you can also display the user information:
Public void readInfo () {// get the content in the info file SharedPreferences sP = getSharedPreferences (info, MODE_PRIVATE); ed_nam.setText (sP. getString (name,); ed_passwd.setText (sP. getString (passwd ,));}
Display Effect: