Virgins Android (13th) --- SharedPreferences and sharedpreferences for lightweight Android Data Storage

Source: Internet
Author: User

Virgins Android (13th) --- SharedPreferences and sharedpreferences for lightweight Android Data Storage



I. Preface



Reprinted please indicate the source: http://blog.csdn.net/wlwlwlwl015/article/details/42437007

When I was a beginner in Android, I used the Intent + Bundle mode to transfer values between activities. At first, I felt that there was nothing to do with it. Later I gradually discovered the drawbacks, that is, I could only pass values layer by layer, when several of my activities need to retrieve data from one Activity, it seems quite limited. It is troublesome and unreasonable to transmit data, later I thought about whether there is something similar to Session in Android web development. As long as the Session is not over, data can be shared among multiple jsp pages, which is quite convenient, after reading the relevant information, I found that SharedPreferences is what I was looking for. I recorded the process of learning it through this blog and thoroughly solved the lightweight data storage problems encountered in all future projects.



Ii. Create SharedPreferences



First, let's take a look at the overview of SharedPreferences in the official documentation:


SharedPreferences provides a framework that allows us to save or read key-value pairs of basic data types, you can use SharedPreferences to save any basic data types, such as Boolean, floating point, integer, long integer, and string. Data saved in SharedPreferences can be saved "across Seesion" (or even your application has been destroyed ).


After reading this section, we should have understood the role of SharedPreferences. After reading this section, I will briefly summarize the following three points:

1. SharedPreferences stores data in the format of key-value pairs, similar to Map sets.

2. SharedPreferences the data types that can be stored are basically basic data types.

3. The data stored in SharedPreferences does not depend on the context (it can be guessed that it must be saved in the file, which will be discussed later ).


Now let's take a look at how to get the SharedPreferences object and continue reading the document, next to the above section:


Obviously, we have two options: getSharedPreferences () or getPreferences ().

For a brief look, the first method is to create multiple parameter files andDistinguish by name attribute (name is the first parameter you specified)The second method can only create a parameter file for the current Activity without specifying the name, because it can only act on the current Activity. Obviously, we need to use the first one, because we need to share data between multiple activities. Next, let's take a 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 correct, that is, the name specified for SharedPreferences (the document translation marked with the underline above), and the second parameter is an integer mode, for details, refer to the official explanation in APIs:


The blue lines mark all the modes. Therefore, we can select any of the four parameters as the second parameter. Of course, the specific parameters are as follows, the following describes the applicable scenarios of the four modes officially provided.

1. MODE_PRIVATE

Use 0 or MODE_PRIVATE for the default operation. for translation, Use 0 or MODE_PRIVATE as the default operation. In general, we can set this MODE. In fact, this MODE specifies that the SharedPreferences data can only be read and written by this application. In most cases, this is what we need.

2. MODE_WORLD_READABLE

Specify that the SharedPreferences data can be read by other applications, but cannot be written. In some cases, this permission is quite useful, for example, when an application needs to obtain data from another application.

3. MODE_WORLD_WRITEABLE

In this mode, the "writable" permission is added to the above mode. This mode should not be used without special requirements.

4. MODE_MULTI_PROCESS

This mode allows you to change the same SharedPreferences file among multiple processes. It is usually used in Android 2.3 and earlier versions, so we will not introduce it here.

OK. After learning about the methods for instantiating the SharedPreferences object and the meanings of parameters, You Can instantiate the SharedPreferences object as needed. By the way, the getSharedPreferences () method obtains the object in singleton mode.



3. write and read data



Since SharedPreferences is a data storage object, what should be done first after the object is instantiated is to write data. As for how to write the object, continue reading the document without jumping lines, then I posted the post To get... start with the following code:


Three steps are as follows:

1. Call the edit () method to obtain the Editor object.

2. Store the value through the putXxx method of the Editor object.

3. Call the commit () method of the Editor object to submit and save.

First of all, we need to make it clear that writing data is implemented through the Editor object, and the Editor object is provided by the SharePreferences object, so there is nothing to say, below is 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 btnToOtherActy; 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 the SharedPreferences object SharedPreferences perferences = context. getSharedPreferences ("userInfo", Context. MODE_PRIVATE); // get the content input by EditText String username = etUsername. getText (). toString (); String password = etPassword. getText (). toString (); // obtain the Editor object Editor = perferences. edit (); // Save the value editor. putString ("username", username); editor. putString ("password", password); // submit and save the editor. commit (); startActivity (new Intent (MainActivity. this, SecondActivity. class ));}});}}
The interface is very simple. With only two EditText and one Button, no code is pasted. The Activity is also very simple, that is, get the input value and save it to SharedPreferences, we can see that the last row jumps to another Activity. In fact, I just want to display the value in another Activity. There is a deposit that must be fetched to verify whether it is saved and whether it can be retrieved. Paste the SecondActivity code to see how to set the 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);}}

It is very easy to get the corresponding value based on the key by using the getXxx method of SharedPreferences. Run the program to check whether the value is displayed normally:



BINGO seems to work very well. Through SharedPreferences, we have successfully passed values between two activities.



Iv. storage location of SharedPreferences



As mentioned before, SharedPreferences actually stores data in a file. What is the file format and where is the file? These problems must also be clarified. After the program runs, we enter the DDMS view in eclipse. After switching, we select the "File Explorer" Panel. The first entry may take a moment. loading the File list takes a small amount of time, then we can see the file structure:


Note that the path has been marked, because the data of SharedPreferences is always stored in

/Data/<package name>/shared_prefs

In this path, after entering this path, we can find such a file:


Yes. In fact, the key-value pair of SharedPreferences is saved in this xml file, and the first parameter of the getSharedPreferences () method is the file name of this xml file. Finally, click "Pull a file from the device" in the upper right corner to pull the xml file to the computer and open it for a look:


If the data is stored in the key-value format through an xml file, this is consistent with all the guesses we mentioned above.

Note that if no File is found in the data folder under the root directory of File Explorer, or you can open it but cannot see any File, generally, this is because the mobile phone does not have the ROOT permission. We recommend that you debug it through a virtual machine.



V. SharedPreferences combined with custom Application applications



In actual projects, we will basically operate sharedpreferences with a custom application. Although sharedpreferences does not depend on context, it is still advantageous and convenient to do so, I personally think there are two advantages:

1. simplified the Data Reading Process.

2. Improved Data Reading performance.

For example, in an APP with the logon function, user information is usually stored in SharedPreferences after successful logon, and you do not have to log on to the APP the next time you enter the APP. In combination with this instance, I will analyze the two points mentioned above in sequence.


First, the Data Reading Process is simplified.

If you do not use the application, you must first obtain the SharedPreferences object through the context object of the current Activity to read data in the Activity, and then use preferences. getXxx to obtain the value. If we define an object in the Custom application to encapsulate user information, read the data in the onCreat () method of the application and assign the value to the object, in the entire application running process, you only need to get the application object and then set the value to OK, saving the code line for obtaining the SharedPreferences object.


Second, it improves data reading performance.

If you do this in the above way, you only need to access SharedPreferences once during the program running, and then retrieve data from the application in the memory. If you do not need the application, then, we need to access the xml file through SharedPreferences every time to obtain data. One is to read data from the memory, and the other is to read data from the file. Which one is faster and more obvious.


The above two points are my personal conclusions through practical application analysis. After all, I am a newbie. Some questions are not necessarily correct or accurate, in case of any errors, please criticize and correct them.


Finally, I will paste a piece of code used by the application in combination 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();public UserEntity getUserEntity() {return 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,""));}}

We can see that each time the application starts, it will first read data from SharedPreferences. In this way, if there is data, it is very convenient for other activities to use data, directly through application. getUserEntity. getXxx takes the value. The write and delete operations on SharedPreferences are encapsulated as follows:

/*** Store user logon information ** @ param mApp * @ param sp * @ param userEnt */public static void saveLoginUserinfo (MyApplication mApp, SharedPreferences 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 logon information ** @ param mApp */public static void clearUserLoginInfo (MyApplication mApp) {SharedPreferences sp = mApp. getSharedPreferences (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, the data in the memory should be consistent after the data is written. Now, the introduction to SharedPreferences is provided in the section. The use of SharedPreferences is very simple. If you have more in-depth application and understanding, you will continue to update this blog.



Vi. Summary



I have always wanted to learn this, but there is always no time, because SharedPreferences are too common, such as data sharing and transmission between activities, or persistence of lightweight data, for the first time, I learned something that may not be easy or unstandard. I welcome all the experts to criticize and correct it, because only continuous correction of errors can improve, and I hope that I will leave the Android cainiao stage as soon as possible, this point should also be washed and sleep. We may have to summarize the hibernate optimization technologies from tomorrow. If we have time, we will share it in the form of a blog. We will be here today, continue to work hard. Come on, Raito!



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.