In the last two sections we are using text files to save the user's information, which is obviously a loophole. At the same time, the content of the file is not managed. Today we learn to save with Sharedpreference. Sharedpreference is dedicated to preserving some of the more fragmented data.
We still use the example of the previous section to analyze the user's information using Sharedpreference to save.
Note: If you do not know what the example is, see Android storage Learning to read and write files in internal storage
When the OK button is clicked, the user's information is saved:
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 entered if ((Name.equals ("")) | | (Passwd.equals (""))) {Toast.maketext (this, "User name or password cannot be empty", Toast.length_short). Show (); else {if (cb.ischecked ()) {//uses sharedpreference to hold the user's information, the default path for//sharedpreference is:/share_prefs/in the current process package name Sharedpreferences sp = getsharedpreferences ("info", mode_private);//Get sharedpreference Editor editor = Sp.edit (); Editor.putstring ("name", name), editor.putstring ("passwd", passwd);//Submit Editor.commit ();} Toast.maketext (This, "Login successful", Toast.length_short). Show ();}}
You can see that there is an info file under the sharedpreference path
Export can be seen. Info.xml is saved in the form of Key,value.
<?xml version= ' 1.0 ' encoding= ' utf-8 ' standalone= ' yes '? ><map><string name= "passwd" >1233333</ string><string name= "Name" >ert</string></map>
When you come in again, you can also echo the user's message:
public void Readinfo () {//Gets the contents of the info file sharedpreferences SP = getsharedpreferences ("info", mode_private); ed_ Nam.settext (sp.getstring ("name", "")), Ed_passwd.settext (sp.getstring ("passwd", ""));}
Display effect:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Storage Learning using sharedpreference save file