First, preface
Reprint please indicate source: http://blog.csdn.net/wlwlwlwl015/article/details/42437007
Beginner Android When the transfer value between activity I was using intent+bundle this mode to achieve, just beginning to feel nothing, and then gradually found the drawbacks, that is, can only pass by layer, When several of my activity needs to take data from an activity, this is quite limited, the transmission of the trouble, and unreasonable, and then want to have in the Android Web development similar to the session of the thing, as long as the conversation does not end, Then in a number of JSP pages can be arbitrarily shared data, so it is quite convenient to consult the relevant information, found that sharedpreferences is what I am looking for, through this blog record I learn it process, and completely solve the problem of lightweight data storage encountered in all future projects.
Ii. creation of Sharedpreferences
First look at an overview of sharedpreferences in the official documentation:
As a whole, Sharedpreferences provides a framework that allows us to save or read key-value pairs of data of basic data types , and you can use Sharedpreferences to save data of any basic data type. For example: Boolean type, float, integer, Long Integer, and string type. The data saved in Sharedpreferences can be saved "across Seesion" (even if your application has been destroyed).
After reading this paragraph, we should have already understood the role of sharedpreferences, and after reading it, I briefly summed up the following three points:
The 1.SharedPreferences saved data format is the key-value key-value pair format, similar to the map collection.
2.SharedPreferences the types of data that can be saved are basically basic data types .
The data saved in 3.SharedPreferences does not depend on the context (guess you can guess it's saved in the file anyway).
Well, then it's time to see how to get the Sharedpreferences object and keep looking at the document, next to the paragraph above:
Obviously, we have 2 options, respectively, by getsharedpreferences () or getpreferences ().
For a simple look, the first is that you can create multiple parameter files, differentiate by the name attribute (name is the first parameter you specify), and the second can only create a parameter file for the current activity, and you do not need to specify name. Because it can only be used for the current activity. Obviously, we need to use the first one, because we need to share data between multiple activity. So here's a concrete look at this method:
Package Com.wl.sharedpreferencesdemo;import Com.example.sharedpreferencesdemo.r;import android.app.Activity; Import Android.content.context;import Android.content.sharedpreferences;import Android.os.bundle;public class Mainactivity extends Activity {private context context; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); context = this; Sharedpreferences sharedpreferences = context.getsharedpreferences ("Curruserinfo", Context.mode_private);}}
The first parameter is no problem, the name we specified for sharedpreferences (the document translated by the underscore above), and the second parameter is an integer mode, see the official APIs for explanations:
Blue Line is all the mode, so say the second parameter we can choose any of these 4 kinds of, of course, specific or look at the demand, the following respectively explain the official given the 4 kinds of mode of application occasions.
1.mode_private
Use 0 or mode_private for the default operation, translate it, using 0 or Mode_private as the defaults. That is to say that normally we set this mode, in fact, this mode specifies that the sharedpreferences data can only be read and written by the application , in most cases our needs should be like this.
2.mode_world_readable
Specifies that the sharedpreferences data can be read by other applications, but cannot be written. In some cases this permission is quite useful, such as when an application needs to fetch data from another application.
3.mode_world_writeable
This mode is to append the "writable" permission in the above mode, and no special requirement should not use this mode.
4.mode_multi_process
This mode allows you to change the same sharedpreferences file between multiple processes, which is usually used in Android 2.3 and below, so this is not an introduction.
OK, the method of instantiating the Sharedpreferences object and the meaning of the parameter are understood, then the Sharedpreferences object can be instantiated according to the requirement. Incidentally, the Getsharedpreferences () method is to get the object by using a singleton pattern .
Third, write & read data
Since sharedpreferences is the object of data storage, then the first thing to do after instantiating the object is to write the data, as to how to write, continue to read the document, not skip, and then I posted above the section to get ... Look down at the beginning:
Clear three steps:
1. Call the edit () method to get the editor object.
2. The value is stored through the Putxxx method of the editor object.
3. Invoke the Commit () method of the Editor object to commit the save.
First of all, we have to make it clear that writing data is achieved through the Editor object, and the editor object is exactly what the Sharepreferences object provides, and it feels like there's nothing more to say, so here's a short sample code:
Package Com.wl.sharedpreferencesdemo;import Android.app.activity;import Android.content.context;import Android.content.intent;import Android.content.sharedpreferences;import Android.content.SharedPreferences.Editor; Import Android.os.bundle;import android.view.view;import android.widget.button;import android.widget.EditText; public class Mainactivity extends Activity {private EditText etusername;private EditText etpassword;private Button Btntoo Theracty;private context context; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); context = This;etusername = (EditText) Findviewbyid ( R.id.et_username) Etpassword = (EditText) Findviewbyid (r.id.et_password); btntootheracty = (Button) Findviewbyid ( R.ID.BTN_TO_OTHER_ACTY); Btntootheracty.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {//Get Sharedpreferences object sharedpreferences perferences = context.getsharedpreferences ("UserInfo", COntext. mode_private);//Gets the contents of the EditText input string username = Etusername.gettext (). toString (); String password = Etpassword.gettext (). toString ();//Get Editor Object Editor editor = Perferences.edit ();// Stored value editor.putstring ("username", username) editor.putstring ("password", password);//Submit Save Editor.commit (); StartActivity (New Intent (Mainactivity.this,secondactivity.class));}});}The interface is very simple, only put 2 edittext and a button, do not paste code, activity do things is very simple, is to get the input value and save to Sharedpreferences, Can see the last line to jump to another activity, in fact, I just want to in another activity to value display, there must be taken, so as to verify whether it is saved, can be taken. By the way, paste the secondactivity code to see how to Value:
package Com.wl.sharedpreferencesdemo;import Android.app.activity;import Android.content.context;import Android.content.sharedpreferences;import Android.os.bundle;import Android.widget.textview;public Class Secondactivity extends Activity {private TextView tvusername;private TextView tvpassword;private Context context;@ overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); Setcontentview (r.layout.second); context = This;tvusername = (TextView) Findviewbyid (r.id.tv_ username); Tvpassword = (TextView) Findviewbyid (R.id.tv_password); Sharedpreferences preferences = context.getsharedpreferences ("UserInfo", context.mode_private); String username = preferences.getstring ("username", "" "); String Password = preferences.getstring ("Password", "" "); Tvusername.settext (username); tvpassword.settext (password);}}
Very simple, directly through the Sharedpreferences GetXXX method can be based on key to obtain the corresponding value. Now run the program to see if you can display the values normally:
BINGO, it seems to work very well, we successfully achieved the value of two activity between activities through Sharedpreferences.
Iv. storage location of Sharedpreferences
also mentioned before Sharedpreferences actually is the data exists in the file, then what is the file format, where does the file exist? These are the problems that we have to figure out. After the program runs, we enter the Ddms view in Eclipse, switch to the past and select the "file Explorer" panel, the first entry may take a moment, file list loading takes a little time, and then we can see the file structure:
The path that needs attention I have marked out, because the sharedpreferences data is always saved in
/data/data/<package Name>/shared_prefs
Under this path, after entering this path we can find such a file:
Yes, it is in this XML file to save the Sharedpreferences key-value key value pairs, and the Getsharedpreferences () method of the first parameter is the file name of this XML file. Finally click on the "Pulla filefrom the device" in the upper right corner to pull the XML file onto your computer and open it to look at:
It is true that the data is stored in the Key-value format through an XML file, which is consistent with the various guesses we have mentioned earlier.
Finally, it should be noted that if you do not find any files under the Data folder in the root directory of the file Explorer, or you can click to open, but you do not see any files, it is generally the reason that the phone does not have root privileges , it is recommended to debug through the virtual machine.
Five, sharedpreferences combination of custom application application
In the actual project we will basically combine the custom application to operate the sharedpreferences, although sharedpreferences does not rely on the context, but this is still a certain advantage and convenience, I personally think there are the following two points of benefit:
1. The steps to read data are simplified.
2. Improves the performance of data read.
For example, in the app with login function, we will generally sharedpreferences the user information after the login is successful, the next time you enter the application, you do not have to log in. With this example, I'll analyze the two points I mentioned above in turn.
First, the steps for data reading are simplified.
If we do not use application, then in the activity all need to read the data, first through the current activity's context object to get to the Sharedpreferences object, And then go through the preferences.getxxx to fetch the value. If we define an object in the custom application that encapsulates the user's information, the action in application's Oncreat () method sharedpreferences read the data and assign it to the object, Then in the entire application running process only need to get the Application object value is OK, save the Sharedpreferences object to get this line of code.
Second, it improves the performance of data read.
If done in the way above, then in the process of running the program only need to access a sharedpreferences, and then fetch the data can be directly from the memory application, and if not application, So every time you have to access the XML file through the sharedpreferences to get the data, one is read from memory, one is read from the file, which is quickly obvious.
The above two points is my personal analysis through the actual application of the conclusion, after all, I am still a novice, some problems are not necessarily correct, not necessarily accurate, if there are errors in the place also urge you to criticize.
Finally, put a piece of code that application combined with sharedpreferences.
MyApplication:
Package Com.wl.sess;import Com.wl.sess.model.myconstants;import Com.wl.sess.model.userentity;import Android.app.application;import Android.content.context;import Android.content.sharedpreferences;public Class MyApplication extends Application {private userentity userentity = new userentity ();p ublic userentity getuserentity () {RE Turn userentity;} public void setuserentity (Userentity userentity) {this.userentity = userentity;} @Overridepublic void OnCreate () {//TODO auto-generated method Stubsuper.oncreate (); Sharedpreferences sp = getsharedpreferences (myconstants.sp_userinfo,context.mode_private); UserEntity.setUserid ( Sp.getlong (myconstants.sp_userinfo_id,-1)); Userentity.setusername (Sp.getstring (myconstants.sp_userinfo_ USERNAME, "")), Userentity.setuserpassword (Sp.getstring (Myconstants.sp_userinfo_pwd, "")); Userentity.setusertel ( Sp.getstring (Myconstants.sp_userinfo_tel, "")); Userentity.setsessionid (Sp.getstring (myconstants.sp_userinfo_ SESSIONID, ""));}}
It can be seen that the first time the application starts from the sharedpreferences to read the data, so if there is data, then the other activity needs to use the data is very convenient, It's OK to take the value directly from the APPLICATION.GETUSERENTITY.GETXXX. Generally, the write and delete of sharedpreferences are simply encapsulated, and I encapsulate this:
/** * Store User login information * * @param mApp * @param sp * @param userent */public static void Saveloginuserinfo (MyApplication Mapp,sha Redpreferences sp, userentity userent) {Editor sped = Sp.edit (); Sped.putlong (myconstants.sp_userinfo_id, Userent.getuserid ()); Sped.putstring (Myconstants.sp_userinfo_username, Userent.getusername ()); Sped.putString ( Myconstants.sp_userinfo_pwd, Userent.getuserpassword ()); Sped.putstring (Myconstants.sp_userinfo_tel, Userent.getusertel ()); Sped.putstring (Myconstants.sp_userinfo_sessionid,userent.getsessionid ()); Sped.commit (); Mapp.setuserentity (userent);} /** * Clear User login information * * @param mApp */public static void Clearuserlogininfo (MyApplication mapp) {Sharedpreferences sp = MAPP.G Etsharedpreferences (Myconstants.sp_userinfo, context.mode_private); Editor sped = Sp.edit (); Sped.remove (myconstants.sp_userinfo_id); Sped.remove (Myconstants.sp_userinfo_username); Sped.remove (MYCONSTANTS.SP_USERINFO_PWD); Sped.remove (Myconstants.sp_userinfo_tel); Sped.remove (MyConstants.SP_ Userinfo_sessionid); Sped.commit ();}
As you can see, after writing the data, the data in memory should also be consistent. Well, to here about the introduction of sharedpreferences on the paragraph, the current use is very simple, follow-up if there is a deeper application and understanding of the words will continue to update this blog.
Vi. Summary
Always wanted to learn this but there is no time, because sharedpreferences is too often used, such as data sharing and transfer between activity, or the persistence of lightweight data, and so on, the first time to learn some places may be said bad or not standard, welcome the way the Great God criticized, Because only constantly correct mistakes to improve, but also hope that their early off the Android rookie stage, the point should also wash and sleep, tomorrow may start to a good summary of Hibernate optimization related technology, time will also be the form of blog share out, today to here, but also to continue efforts , come on, raito!.
Virgin Male Learn Android (13)---Android Lightweight data storage sharedpreferences