Parse the SharedPreferences store

SharedPreferences introduction:

Many software will have configuration files, which store various attribute values ​​during the running of the program. Since there is not much configuration information, it is not cost-effective to use the database to store, because the time-consuming of database connection and operation will greatly affect the efficiency of the program. Therefore, we use a one-to-one correspondence between key and value to store these configuration information. SharedPreferences is the technology used in Android to implement this storage method.

 

The use of SharedPreferences is very simple and can easily store and read data. SharedPreferences can only hold simple types of data, such as String, int, etc. Generally, complex types of data are converted into Base64 encoding, and then the converted data is saved in an XML file in the form of a string, and then saved in SharedPreferences.

 

 
 
      The steps to save key-value pairs using SharedPreferences are as follows:

  (1) Use the getSharedPreferences method of the Activity class to obtain the SharedPreferences object, where the name of the file storing the key-value is specified by the first parameter of the getSharedPreferences method.

 

  (2) Use the edit of the SharedPreferences interface to obtain the SharedPreferences.Editor object.

  (3) Save the key-value pair through the putXxx method of the SharedPreferences.Editor interface. Where Xxx represents different data types. For example: the value of string type needs to use the putString method.

  (4) Save the key-value pair through the commit method of the SharedPreferences.Editor interface. The commit method is equivalent to the commit operation in a database transaction.

 

The specific code writing process is as follows:

 

A. to store data

 

1. Open Preferences, the name is setting, if it exists, open it, otherwise create a new Preferences

SharedPreferences settings = getSharedPreferences(“setting”, 0);

 

2. Let the setting be in the editing state

SharedPreferences.Editor editor = settings.edit();

3. Store data

editor.putString(“name”,”ATAAW”);


editor.putString("URL","ATAAW.COM");

 

4. Complete the submission

 

editor.commit();

 

B, read data information

 

1. Get Preferences

SharedPreferences settings = getSharedPreferences(“setting”, 0);

 

2. Take out the data

String name = settings.getString("name","default");


String url = setting.getString(“URL”,”default”);

 

The above is how to use SharedPreferences in Android. The location of the created Preferences file can be viewed in Eclipse:

DDMS->File Explorer /<package name>/shared_prefs/setting.xml

 
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326833573&siteId=291194637