[Android Note 9] Android sharedpreferences enables user preference Storage

Source: Internet
Author: User

In the process of developing an application, sometimes we need to record user preferences, or username and password. This involves data storage. There are several ways to store data on the Android platform:

Shared preferences
Store private primitive data in key-value pairs. lightweight storage in the form of key-value pairs
Internal Storage
Store private data on the device memory. File storage on the device
External Storage
Store public data on the shared external storage. External file storage, usually refers to the files stored on the SD card, the advantage is that it is not deleted with the program uninstallation
SQLite Databases
Store structured data in a private database. This is a common database.
Network Connection
Store data on the web with your own network server. Obtain the network

Today, we will share with you the first kind of referepreference, which is a lightweight data storage framework provided by Android in the form of key-value pairs, friends familiar with XML should be familiar with this style, which is in the form of "attribute name-attribute value. It can be seen from the name that this framework is mainly used to set a user's preference. It features cross-session sharing and operation between multiple activities, if you set special permissions, other applications can also access them. The following is a basic method.

1: Get typeSharedPreferences 

There are two main ways to obtain

 

  • getSharedPreferences()Two parameters are accepted. The first parameter is the file ID, and the second parameter is the permission used to create multiple configuration files.
  • getPreferences()-Only the File Permission parameter. Unlike the previous one, only one file is created.

The first method is described in detail today ~

First, let's take a look at the introduction from the official API.

Public abstract sharedpreferences getsharedpreferences (string name,
Int Mode)

Retrieve and hold the contents of the preferences file 'name', returning a sharedpreferences through which you can retrieve and modify its values. Only one instance of the sharedpreferences object is returned to any callers for
Same name, meaning they will see each other's edits as soon as they are made.

Explanation: This method is used to retrieve and maintain a configuration file named name from the context (which can be understood as our context file and is not unfamiliar to friends who have written various services. Returns a sharedpreferences object. You can use this object to edit and obtain key values. Only one sharedpreferencesd instance is called at each time. The result is that each caller can immediately see the edited results of other callers.

Parameters
Name Desired preferences file. if a preferences file by this name does not exist, it will be created when you retrieve an Editor (sharedpreferences. edit () and then Commit Changes (editor. commit ()).
Explanation: the required file name. If it does not exist, it will be automatically created when you call the Editor (used to edit the preference file, which will be described below.
Mode Operating mode. Use 0 orMODE_PRIVATEFor
The default operation,MODE_WORLD_READABLEAndMODE_WORLD_WRITEABLETo
Control permissions. The bitMODE_MULTI_PROCESSCan also be used
If multiple processes are mutating the same sharedpreferences file.MODE_MULTI_PROCESSIs
Always on in apps targetting gingerbread (Android 2.3) and below, and off by default in later versions.

Explanation: There are four operation modes.

Returns
  • Returns the single sharedpreferences instance that can be used to retrieve and modify the preference values.
See also
  • Mode_private: This is the default form. The configuration file only allows access to the program and the program with the program id.
  • Mode_world_readable allows other applications to read files.
  • Mode_world_writeable allows other applications to write files.
  • Mode_multi_process is mainly used for multi-task tasks. In analyticdb 2.3, this label must be specified when multiple processes are accessed together.

With the sharedpreferences object, we also need an editor to edit and set the preference.

Editor mainly includes some putxxx methods, including booleans, floats, ints, longs, and strings. you must call the commit method or apply method to submit the modified method after adding it.

If you want to get the value, you can directly use the sharedpreference class to use the corresponding getxxx method.

I will share with you a very simple piece of code temporarily written by myself.



Package COM. yui; import android. content. context; import android. content. sharedpreferences; import android. content. sharedpreferences. editor; import android. OS. bundle; import android. preference. preferenceactivity; import android. util. log; /*** demo of Android sharedpreference * @ author octobershiner * @ version 1.0 2011/11/4 **/public class preferactivity extends preferenceactivity {/** called when the activity is first created. * // set some labels Private Static final string my_setting = "mysetting"; Private Static final string color = "color"; Private Static final string default_color = "blue "; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // get the setting files sharedpreferences mypreference = This. getsharedpreferences (my_setting, context. mode_private); // edit the file editor = mypreference. edit (); Editor. putstring (color, "Red");/*** explains this function, when mypreference finds that there is no color attribute, * ult_color will be assigned to temp * You can try to comment out the previous putstring, log records are different **/string temp = mypreference. getstring (color, default_color); // use log to display some results. I ("tag", "Now I prefer" + temp );}}

Finally, I want to ask a question. Xiao o reads the SDK source code of Android 2.3, but finds that sharedpreference is only an interface and I have not found its implementation, no answers are provided on the Internet. If you want to know more about the problem, please contact me in time. Thank you. At, no one in the lab is ready to go back to bed ~~

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.