Sharedpreferences Analysis of Android data storage

Source: Internet
Author: User

Sharedpreferences is one of the ways in which Android data is stored, and is particularly well-suited for storing small amounts of simple data, such as the application's various configuration information, such as whether to turn on sound effects, whether to turn on vibrations, and so on.

 Sharedpreferences location and format for storing data

Sharedpreferences the data in the form of a key-value pair, stored under the/data/data/<package name>/shared_prefs directory, saved in XML format, the root element of the XML file is <map ... /> Each child element in this element represents a Key-value pair.

 Three ways to get sharedpreferences

To use Sharedpreferences, you first need to get the Sharedpreferences object. Sharedpreferences itself is an interface, so the program cannot directly create Sharedpreferences objects, Android provides three ways to get sharedpreferences objects.

1. Getsharedpreferences (String name, int mode) method for the Context class

The first parameter specifies the file name of the Sharedpreferences, and the second parameter specifies the mode of operation, passing in Mode_private or 0, indicating that only the current application can manipulate the Sharedpreferences file.

2. getpreferences (int mode) method of Activity class

The method accepts only one parameter, which specifies the mode of operation, as in the method above. The Sharedpreferences file name is named after the current Activity's class name. This file belongs to the current activity private, only the current activity can be manipulated.

3, Preferencemanager Class of getdefaultsharedpreferences (context context) method

This is a static method that accepts a Context parameter, naming the Sharedpreferences file as a prefix to the current application's registration, and the entire application can operate.

 Sharedpreferences Accessing data  

    Methods in the Sharedpreferences

After you get the Sharedpreferences object, you can read the data. The GetXXX method in the public method provided in Sharedpreferences is read data, such as

GetInt (String key, int defvalue) reads an int data, passing in the first parameter is the key that stores the data, the second parameter is the default value, and the default value is returned when key does not exist.

The GetAll () method returns all the key-value pairs in the sharedpreferences.

Contains (String key) is used to determine whether sharedpreferences all key-value pairs contain key-value pairs with key keys.

In addition, there is an internal interface, Sharedpreferences.onsharedpreferencechangelistener, used to declare a callback, when a sharedpreferences is sharedpreferences This method will be recalled when changing. Sharedpreferences provides the Registeronsharedpreferencechangelistener ( Sharedpreferences.onsharedpreferencechangelistener listener) and Unregisteronsharedpreferencechangeli Stener (Onsharedpreferencechangelistener Listener) to register and unregister the callback separately.

    Methods in the Sharedpreferences.editor

Sharedpreferences also has a method of edit (), which returns Sharedpreferences's other internal interface Sharedpreferences.editor object, which provides a method such as putxxx, which is easily guessed to be written into the data. Also take Putint (String key, int value), which is to write a key-value pair to the Sharedpreferences file. It is worth mentioning that after calling the Putxxx method, you must also call the commit () or the Apply () method to actually write the data, which is easy to forget (I've stepped on the pit while learning Android).

Clear () method to empty all key-value pairs in the sharedpreferences.

The Remove (String key) method, which removes the key-value pair of key keys, calls the Commit method to take effect when this method is called.

Finally there are two methods, void Apply () and Boolean commit (), all of which are actually committing a modification. Here are the main differences between the two methods:

        • From the two methods I have written above, it can be seen that the Apply method does not return a value, and the Apply method does not prompt any failed prompts. The Commit method has a return value indicating whether the change was committed successfully.
        • From the usage, after calling the Putxxx method, the call to apply or the Commit method can be committed, and after calling the Remove (String key) method, the Commit method must be called.
        • In essence, apply is to commit the modified data atoms to memory, and then asynchronously commit to the hardware disk, and commit is synchronous commit to the hardware disk, so in the case of multiple concurrent commit commits, they will wait for the commit to be processed after saving to disk in the operation, Thus reducing the efficiency. While apply is only the atomic commit to the content, the subsequent call to apply the function will directly overwrite the previous memory data, which to a certain extent, improve a lot of efficiency.

Because in a process, sharedpreference is a single instance, there is no concurrency conflict, if you do not care about the results submitted, it is recommended to use apply, of course, you need to ensure that the submission is successful and follow-up, or need to use a commit. Here is a simple example of the layout of stationery as follows:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"android:orientation= "vertical"Tools:context= "Com.example.joy.sptest.MainActivity">    <TextViewAndroid:id= "@+id/tv_show"Android:layout_margintop= "20DP"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center_horizontal"Android:text= "Hello world!" />    <ButtonAndroid:id= "@+id/btn_write"Android:layout_margintop= "10DP"android:layout_gravity= "Center_horizontal"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:onclick= "OnClick"Android:text= "Write Data"/>    <ButtonAndroid:id= "@+id/btn_read"Android:layout_margintop= "10DP"android:layout_gravity= "Center_horizontal"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:onclick= "OnClick"Android:text= "Read Data"/>    <ButtonAndroid:id= "@+id/btn_modify"Android:layout_margintop= "10DP"android:layout_gravity= "Center_horizontal"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:onclick= "OnClick"Android:text= "Modify Data"/></LinearLayout>

The program code is as follows:

 Packagecom.example.joy.sptest;Importandroid.content.SharedPreferences;ImportAndroid.preference.PreferenceManager;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsappcompatactivity {PrivateTextView tvShow; PrivateSharedpreferences sp; PrivateSharedpreferences.editor Editor; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); TvShow=(TextView) Findviewbyid (r.id.tv_show); }     Public voidOnClick (View v) {SP= Preferencemanager.getdefaultsharedpreferences (mainactivity. This); Switch(V.getid ()) { CaseR.id.btn_write:editor=Sp.edit (); Editor.putstring ("Name", "Zhangsan"); Editor.putint ("Age", 18); if(Editor.commit ()) {Toast.maketext (mainactivity). This, "Submit success!", Toast.length_short). Show (); } Else{toast.maketext (mainactivity). This, "Submission failed!", Toast.length_short). Show (); }                 Break;  Caser.id.btn_read:string name= sp.getstring ("name", "Xiaoming"); intAge = Sp.getint ("Age", 0); Tvshow.settext ("Student Name:" + name + "Student Age:" +Age );  Break;  CaseR.id.btn_modify:editor=Sp.edit (); Editor.putstring ("Name", "Zhang San"); if(Editor.commit ()) {Toast.maketext (mainactivity). This, "Submit success!", Toast.length_short). Show (); } Else{toast.maketext (mainactivity). This, "Submission failed!", Toast.length_short). Show (); }                 Break; }    }}

A TextView, the first run will show the default "Hello world!", there are three buttons below, click Write data, call Sharedpreferences, write data, click to read the data, from Sharedpreferences the data is read and displayed on the TextView, click Modify Data, then write the same key again, replacing the previous value. The results of the program run as follows:

                

The program runs TextView display the default "Hello world!", click to read the data, because the key is not found, so return the specified default value, click Write data, write the name "Zhangsan", age "18". Click Edit Data to change the name to "Zhang San".

Can be viewed through the Ddms file,

                

An XML file was generated under the Data/data/com.example.joy.sptest/shared_prefs directory: Com.example.joy.sptest_preferences.xml. To export the file, open to see the following:

                

Finally, I post my own package of commonly used reading and writing sharedpreferences methods:

 Public Static voidputsharedpreferences (context context, string key, Object value) {String type=Value.getclass (). Getsimplename (); Sharedpreferences sharedpreferences=preferencemanager.getdefaultsharedpreferences (context); Sharedpreferences.editor Editor=Sharedpreferences.edit (); if("Integer". Equals (Type)        {Editor.putint (key, (Integer) value); } Else if("Boolean". Equals (Type)        {Editor.putboolean (key, (Boolean) value); } Else if("String". Equals (Type)        {editor.putstring (key, (String) value); } Else if("Float". Equals (Type)        {Editor.putfloat (key, (Float) value); } Else if("Long". Equals (Type)        {Editor.putlong (key, (Long) value);    } editor.commit (); }     Public StaticObject Getsharedpreferences (context context, string key, Object defvalue) {String type=Defvalue.getclass (). Getsimplename (); Sharedpreferences sharedpreferences=preferencemanager.getdefaultsharedpreferences (context); //Defvalue is the default value and returns it if the data is not currently available        if("Integer". Equals (Type) {            returnSharedpreferences.getint (Key, (Integer) defvalue); } Else if("Boolean". Equals (Type) {            returnSharedpreferences.getboolean (Key, (Boolean) defvalue); } Else if("String". Equals (Type) {            returnsharedpreferences.getstring (Key, (String) defvalue); } Else if("Float". Equals (Type) {            returnsharedpreferences.getfloat (Key, (Float) defvalue); } Else if("Long". Equals (Type) {            returnSharedpreferences.getlong (Key, (Long) defvalue); }        return NULL; }

Sharedpreferences Analysis of Android data storage

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.