Store data in preference files and preference files

Source: Internet
Author: User

Store data in preference files and preference files

SharedPreferences objects use common XML files to store data in the data directory of applications. The structure of the XML file is very simple, because it only allows the storage of key/value pairs, but Android API also provides a very convenient abstraction, allowing developers to read and write data in a type-safe manner.

The simplest way to create a SharedPreferences object is to use the PreferenceManager. getdefasharsharedpreferences () method, which returns the Default preferences of the application. It is convenient to use this method to store the main preference settings, because the framework automatically manages the file name. However, if an application has multiple preference files, it is best to use the Context. getSharedPreference () method, which allows developers to freely name files. If you only create a preference file related to the Activity, you can use the Activity. getPreference () method to obtain the name of the Activity during the call.

PreferenceManager. getdefasharsharedpreferences () the preference file name is composed of the package name and the suffix _ preferences, such as com. liyuanjinglyj. code_preferences. Although this name is rarely needed, it is important to implement a file backup proxy.

SharedPreferences supports int, float. long. boolean, String, and set <String> objects. The key name must be a valid string. A common practice is to use the dot symbol to structure multiple key values in a group.

For example, if the preference file contains values used for network configuration and user interface settings, You can group them by adding a network or ui prefix for each key. In this way, developers can easily manage key/value pairs to avoid name conflicts. The following example demonstrates how to use a prefix and define a key in a separate Java interface file to structure preference data:

public interface Constants {    public static final String NETWORK_PREFIX = "network.";    public static final String UI_PREFIX = "ui.";    public static final String NETWORK_RETRY_COUNT            = NETWORK_PREFIX + "retryCount";    public static final String NETWORK_CONNECTION_TIMEOUT            = NETWORK_PREFIX + "connectionTimeout";    public static final String NETWORK_WIFI_ONLY            = NETWORK_PREFIX + "wifiOnly";    public static final String UI_BACKGROUND_COLOR            = UI_PREFIX + "backgroundColor";    public static final String UI_FOREGROUND_COLOR            = UI_PREFIX + "foregroundColor";    public static final String UI_SORT_ORDER            = UI_PREFIX + "sortOrder";    public static final int SORT_ORDER_NAME = 10;    public static final int SORT_ORDER_AGE = 20;    public static final int SORT_ORDER_CITY = 30;}

We recommend that you use the above method to access the stored preference value, instead of hard coding the key name in the code. This avoids misspelling and reduces bugs caused by spelling.

The following code demonstrates using the previously defined Constants class to access the preference file:

private void readUiPreferences() {    SharedPreferences preferences            = PreferenceManager.getDefaultSharedPreferences(this);    int defaultBackgroundColor = getResources().            getColor(R.color.default_background);    int backgroundColor = preferences.getInt(            Constants.UI_BACKGROUND_COLOR,            defaultBackgroundColor);    View view = findViewById(R.id.background_view);    view.setBackgroundColor(backgroundColor);}

To modify the value stored in the preference file, you must first obtain the Editor instance, which provides the corresponding PUT method and the method for submitting the modification. Before Android, you can use the commit () method to submit the changes to the storage device. However, in Version 2.3, Editor provides the apply () method for asynchronous write operations. Because we should try to avoid blocking operations in the main thread, the apply () method is better than the previous commit () method. This makes it safe to update SharedPreferences directly from the UI in the main thread.

public void doToggleWifiOnlyPreference(View view) {    SharedPreferences preferences = PreferenceManager.            getDefaultSharedPreferences(this);    boolean currentValue = preferences.            getBoolean(Constants.NETWORK_WIFI_ONLY, false);    preferences.edit()            .putBoolean(Constants.NETWORK_WIFI_ONLY, !currentValue)            .apply();}

The code above shows how to use the click listener to switch the preference values stored in Constants. NETWORK_WIFI_ONLY. If you use the previous commit () method, the main thread may be blocked, resulting in poor user experience. You do not need to worry about the above issues when using the apply () method.

In the same process, each preference file only has instances. So even if two different components use the same name to get two SharedPreference objects, they actually share the same instance, so changes to one object will immediately affect the other object.

To receive a notification when the preference value is modified, the developer needs to register a listener callback function that triggers the listener callback function whenever the apply () or commit () method is called. The most common example is that modifying the preference value in the Activity should affect the behavior of the Background Service, as shown below:

Public class NetworkService extends IntentService implements SharedPreferences. OnSharedPreferenceChangeListener {public static final StringTAG= "NetworkService"; private boolean mWifiOnly; public NetworkService () {super (TAG) ;}@ Override public void onCreate () {super. onCreate (); SharedPreferences preferences = PreferenceManager. getdefasharsharedpreferences (this); preferences. registerOnSharedPreferenceChangeListener (this); mWifiOnly = preferences. getBoolean (Constants.NETWORK_WIFI_ONLY, False) ;}@ Override protected void onHandleIntent (Intent intent) {ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService (CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager. getActiveNetworkInfo (); int type = networkInfo. getType (); if (mWifiOnly & type! = ConnectivityManager.TYPE_WIFI) {Log. d (TAG, "Only run WIFI network"); return;} invoke mnetworkoperation (intent) ;}@ Override public void onSharedPreferenceChanged (SharedPreferences preferences, String key) {if (Constants.NETWORK_WIFI_ONLY. Equals (key) {mWifiOnly = preferences. getBoolean (Constants.NETWORK_WIFI_ONLY, False); if (mWifiOnly) {cancelNetworkOperationIfNecessary () ;}}@ Override public void onDestroy () {super. onDestroy (); SharedPreferences preferences = PreferenceManager. getdefasharsharedpreferences (this); preferences. unregisterOnSharedPreferenceChangeListener (this);} private void cancelNetworkOperationIfNecessary () {// cancel the network operation. } Private void initialize mnetworkoperation (Intent intent) {// Network Operation }}

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.