This should be the simplest way for Android to read and write external data. His usage is basically the same as in J2SE (Java.util.prefs.Preferences), in a simple, transparent way to save some user personalization font, color, location, and other parameter information. General applications provide such interfaces as "settings" or "preferences", which can then be saved through preferences, and the programmer does not need to know exactly what form it is saved in and where it is stored. Of course, if you are willing to save something else, there is no limit. I just don't know what the problem is with performance.
In the Android system, this information is stored in the/data/data/package_name/shared_prefs directory as an XML file.
Data read
1 String prefs_name = "Note.sample.roiding.com"; 2 sharedpreferences settings = getsharedpreferences (prefs_name, 0); 3 Boolean false ); 4 String hello = settings.getstring ("Hello", "Hi");
In this piece of code:
- Sharedpreferences settings = getsharedpreferences (prefs_name, 0);
By name, get a sharedpreferences, as the name implies, this preferences is shared, shared scope according to the same package now, which said that the package and Java inside the package is different, It seems that the package is in the Androidmanifest.xml file:1 <manifest xmlns:android= "Http://schemas.android.com/apk/res/android"2package = " Com.roiding.sample.note "3 android:versioncode=" 1 "4 android:versionname=" 1.0.0 ">
The package inside. According to the results of my present experiment, it is like this, please correct me. The latter int is used to declare the read-write mode, regardless of so many, and temporarily know set to 0 (Android.content.Context.MODE_PRIVATE).
- Boolean silent = Settings.getboolean ("Silentmode", false);
Get a Boolean value and you'll see the benefits of using preferences: You can provide a default value. That is, if the value does not exist in the preference, then use the following value as the return point, thus omitting our if what is null judgment.
Data Write
1 String prefs_name = "Note.sample.roiding.com"; 2 sharedpreferences settings = getsharedpreferences (prefs_name, 0); 3 sharedpreferences.editor Editor = settings.edit (); 4 true ); 5 editor.putstring ("Hello", "hello~"); 6 editor.commit ();
With the above data read code, this is easy to understand, just don't forget the final commit ();
Instance:
For details, please see reprint: http://www.cnblogs.com/linzheng/archive/2011/01/22/1942073.html
Data access in Android-mode one: Preference (config)