(Android review) usage of SharePreferences, androidshare

Source: Internet
Author: User

(Android review) usage of SharePreferences, androidshare


Typical application scenarios:

After entering a page, the default value is displayed (in fact, this can be specified directly in the layout file)


Basic points:

1) The file generated by SharePreferences still exists in/data/application package name/pai_prefs/xxx. xml in the form of a. xml file.

2) SharePreferences is suitable for storing key-value data.


Basic usage:

Storage:

Editor editor = sp. edit (); // get the editor. putString ("name", name); // store data (you have not entered the file) editor. putString ("phone", phone); editor. putString ("email", email); editor. commit (); // submit changes (similar to transactions)

Take:

Sp = getSharedPreferences ("data", MODE_PRIVATE); // get the object, pointing to the current application by default. the file name is data. xml, mode private // sp = getPreferences (MODE_PRIVATE); // The generated file name is MainActivity. xmlet_name.setText (sp. getString ("name", ""); et_phone.setText (sp. getString ("phone", ""); et_email.setText (sp. getString ("email ",""));


Resolution: Why is the file name generated when getPreferences (MODE_PRIVATE) is MainActivity. xml ?? As shown in:



In fact, I mentioned in my previous blog that this kind of function is very similar. In the underlying implementation, it is very likely that you call me and I will call you... Without any secret in front of the source code .. Now let's look at the two functions in the Android source code...


Source code analysis:

First read getSharedPreferences (String name, int mode ):

 @Override    public SharedPreferences getSharedPreferences(String name, int mode) {        return mBase.getSharedPreferences(name, mode);    }


Next, let's take a look at getPreferences (int mode ):

 /**     * Retrieve a {@link SharedPreferences} object for accessing preferences     * that are private to this activity.  This simply calls the underlying     * {@link #getSharedPreferences(String, int)} method by passing in this activity's     * class name as the preferences name.     *      * @param mode Operating mode.  Use {@link #MODE_PRIVATE} for the default      *             operation, {@link #MODE_WORLD_READABLE} and      *             {@link #MODE_WORLD_WRITEABLE} to control permissions.     *     * @return Returns the single SharedPreferences instance that can be used     *         to retrieve and modify the preference values.     */    public SharedPreferences getPreferences(int mode) {        return getSharedPreferences(getLocalClassName(), mode);    }

The getLocalClassName () function is used in the getPreferences (int mode) method. In fact, this function does not need to look at its source code. simply by looking at its name, it knows what it is doing: get the name of the current Activity .... But now that we see this, let's take a look at how the source code is written.

/*** Returns class name for this activity with the package prefix removed. * This is the default name used to read and write settings. ** @ return The local class name. */public String getLocalClassName () {final String pkg = getPackageName (); final String cls = mComponent. getClassName (); // get long class name: package name + class name int packageLen = pkg. length (); if (! Cls. startsWith (pkg) | cls. length () <= packageLen | cls. charAt (packageLen )! = '.') {Return cls;} return cls. substring (packageLen + 1); // capture the section after the package name. That is, the class name}





Example:

1. MainActivity

Package com. example. sharepreferencetest; import android. OS. bundle; import android. app. activity; import android. content. context; import android. content. sharedPreferences; import android. content. sharedPreferences. editor; import android. view. menu; import android. view. view; import android. widget. editText; public class MainActivity extends Activity {private EditText et_name; private EditText et_phone; private EditText et_email; private SharedPreferences sp; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); et_name = (EditText) findViewById (R. id. nameET); et_phone = (EditText) findViewById (R. id. phoneET); et_email = (EditText) findViewById (R. id. emailET); sp = getSharedPreferences ("data", MODE_PRIVATE); // get the object, pointing to the current application by default. the file name is data. xml, mode private // sp = getPreferences (MODE_PRIVATE); // The generated file name is MainActivity. xmlet_name.setText (sp. getString ("name", ""); et_phone.setText (sp. getString ("phone", ""); et_email.setText (sp. getString ("email", "");} public void onClick (View view) {String name = et_name.getText (). toString (); String phone = et_phone.getText (). toString (); String email = et_email.getText (). toString (); Editor editor = sp. edit (); // get the editor. putString ("name", name); // store data (you have not entered the file) editor. putString ("phone", phone); editor. putString ("email", email); editor. commit (); // submit the modification (similar to a transaction)} @ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

2. main. xml

<? Xml version = "1.0" encoding = "UTF-8"?> <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: orientation = "vertical"> <TextView android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "name"/> <EditText android: id = "@ + id/nameET" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: inputType = "textPersonName"> <requestFocus/> </EditText> <TextView android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = ""/> <EditText android: id = "@ + id/phoneET" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: inputType = "phone"/> <TextView android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "email"/> <EditText android: id = "@ + id/emailET" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: inputType = "textEmailAddress"/> <Button android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: onClick = "onClick" android: text = "Save as default"/> </LinearLayout>


:





The generated data. xml file contains the following content:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map><string name="email">1019648568@qq.com</string><string name="phone">13675173829</string><string name="name">hjd</string></map>



Source code download: http://download.csdn.net/detail/caihongshijie6/7615023





Read sharePreferences developed by android

Int age = sharePreferences. getInt ("Age", 20 );
This statement first finds the data whose key is "Age" from the sharePreferences. If yes, it indicates that you have saved the data in advance, and then take the value corresponding to "Age, that is, the value you saved in advance. If the key is not found to be "Age", the last int age will be assigned to you with the default value 20, that is, it is only a default value, it is used only when the value from the sp object fails.

Insert, that is, save, is also relatively simple:
The method for getting the sp is the same:
SharePreferences sharePreferences = getSharePreferences (PREFERENCE_NAME, MOD); sharePreferences. edit (). putInt ("Age", 28 ). commit (); compared to the code above: If you have previously saved "Age" and saved 28 values, int age = sharePreferences. getInt ("Age", 20 );
Here, the age value must be 28, not 20.


How does android sharePreferences save multiple data?

It is stored in the form of AVP, then multiple AVP are created.

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.