There are four ways to persist data in Android: SQLite database, file storage, Preference, ContentProvider.
Each of the four methods is specialized, and preference is stored in the form of a key-value pair like map, which is best used to store information such as the user's personal settings.
You can use an XML file to configure a setup interface and then display it with a dedicated preferenceactivity. Preferenceactivity is a professional set-up interface, as long as it is assigned a configured XML, it can automatically change the corresponding value of the program according to the Operation preference.
For example, in the Res directory to create an XML folder, and then create a new Seeting.xml file, the contents are as follows:
[HTML]View Plaincopyprint?
- <? XML version= "1.0" encoding="Utf-8"?>
- <preferencescreen xmlns:android="http://schemas.android.com/apk/res/android" >
- <checkboxpreference
- android:defaultvalue="false"
- android:key="Boolean_value"
- android:summary="Save a Boolean value"
- android:title="Checkbox" />
- <edittextpreference
- android:defaultvalue="defaultstring"
- android:key="string_value"
- android:name="EditText"
- android:summary="Save a string"
- android:title="Edit Text" />
- </preferencescreen>
Checkboxpreference corresponds to a Boolean value, and edittextpreference corresponds to a string. Android:key is an identifier and must be unique.
Then create a settingactivity.java that reads as follows:
[Java]View Plaincopyprint?
- Import ANDROID.COM.UI.R;
- Import Android.os.Bundle;
- Import android.preference.PreferenceActivity;
- Public class Settingactivity extends preferenceactivity{
- @Override
- public void OnCreate (Bundle savedinstancestate) {
- super.oncreate (savedinstancestate);
- Addpreferencesfromresource (r.xml.setting);
- }
- }
Code Addpreferencesfromresource (r.xml.setting), which specifies an XML for this preferenceactivity, so that when this interface is opened:
Each time you change the settings of the interface, the program automatically persists to save the new value.
It is also very simple to get the values set in other places in the program, simply by using identifiers, such as getting the values of the identifiers "Boolean_value" and "string_value" above, just
[Java]View Plaincopyprint?
- Boolean booleanvalue = Preferencemanager.getdefaultsharedpreferences (
- This ). Getboolean ("Boolean_value", false);
- String stringvalue = preferencemanager.getdefaultsharedpreferences (this)
- . getString ("String_value", " " ");
can be obtained.
Preferencemanager.getdefaultsharedpreferences (Context) is a static method that acquires a global preference object that is unique anywhere in the program, The second parameter of the Getboolean and GetString methods is the default value, which is the default return value when the key fails to get.