Today suddenly encountered the sharedpreferences problem, although used before, but never in-depth understanding, today by the way in-depth understanding, and summed up, to prevent later forget.
The sharepreferences is a lightweight storage class on the Android platform and is ideal for saving software configuration parameters. For example, Boolean,float,long, int,string data, the use of sharedpreferences to save data, the essence is to use XML files to store data, the path to store the:/data/data/< package name >/shared _prefs.
There are two ways to get the sharedpreferences:
1. Call the Getsharepreferences () method of the context object
2. Call the Activity object's Getpreferences () method
Difference:
The Sharedpreferences object obtained by invoking the Getsharedpreferences () method of the context object can be shared by other components under the same application.
The Sharedpreferences object obtained by invoking the Getpreferences () method of the activity object can only be used in the current activity.
There are four modes of sharedpreferences:
Context.MODE_PRIVATEContext.MODE_APPENDContext.MODE_WORLD_READABLEContext.MODE_WORLD_WRITEABLE
Context.mode_private: Is the default mode, indicates that the file is private data, can only be accessed by the application, in which the file does not exist in the creation of a, if present, write new content will overwrite the original file content.
Context.mode_append: Check if the file exists in this mode and append content . Otherwise, create a new file.
Context.mode_world_readable andcontext.mode_world_writeable is used to control whether other applications have permission to read and write to the file.
Context.mode_world_readable indicates that the current file can be read by another application.
Context.mode_world_writeable: Indicates that the current file can be written by another application.
Save method:
Sharedpreferences preferences = getsharedpreferences ("Student", context.mode_private);
Editor editor = Preferences.edit ();
Editor.putstring ("name", "Zhang San");
Editor.putstring ("Age", "22");
Editor.commit ();
Get sharedpreferences:
Sharedpreferences preferences = getsharedpreferences ("Student", context.mode_private);
String name = preferences.getstring ("name", "Default name");
String age = preferences.getstring ("Age", "0");