An example analysis of Perferences usage in Android programming

  • 2020-10-23 21:12:42
  • OfStack

This article illustrates the use of Perferences in Android programming. To share for your reference, the details are as follows:

Browse the mobile phone /data/data/ directory of each package directory, you will often see an shared_prefs folder, there is a package name _preferences.xml file, this file is to say the protagonist, below referred to as the configuration file;

This file is similar to the role of a configuration file, application 1 some attribute values, such as if your application provides guidance user guide function, then estimates will certainly provide option allows the user to shut down this function, you can place the switch in this file, by the next time you start the value can make the correct display;

The operation of this configuration file mainly USES two classes: PreferenceManager and SharedPreferences. SharedPreferences is used for specific operation of this configuration file, such as taking values from files, writing values to files, etc. PreferenceManager is responsible for managing the configuration files of all applications in the system. It can be used to easily obtain the SharedPreferences object of the file through the application context (Content). How to handle the file path, file name and so on are all managed by 1.

The following is the specific usage:

1. Import package


import android.content.SharedPreferences;
import android.preference.PreferenceManager;

2. Get the object

SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

Write/update


SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("pre_key_words", true);
editor.commit();

Of course, you can also write other types of data here, such as putInt,putString, you can see the methods in ES38en.java...

4, the values

boolean checkedKeyWords = mPrefs.getBoolean("pre_key_words", false);

Notice what value "pre_key_words" sets itself in the file, is it boolean or String? Do not use the wrong function, or 1 will return the second parameter (default value);

SharedPreferences reads and writes the package name _preferences.xml file, much like VC and others read and write ini configuration files

I hope this article has been helpful in Android programming.


Related articles: