Take a little book, remember?
- Take a little book, remember?
- Brief introduction
- Body
- Extended Reading
Target group: Android Beginner without foundation
Knowledge Points: Simple use of the Sharedpreferences class
Goal: Record simple key-value pairs of data
Brief introduction
Body
1. First we need to create a Sharedpreferences class object, the simplest code is as follows
SharedPreferences preferences= getPreferences(Context.MODE_PRIVATE);
The definition of the Getpreferences method comes from the activity class
Context.mode_private constants are configured by default, and in addition to mode_world_readable and mode_world_writeable
2. For writing data about Sharedpreferences, the following example shows how to save a simple int type key-value pair
SharedPreferences preferences= getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = preferences.edit();editor.putInt("index"1);editor.commit();
Sharedpreferences can store a variety of data types, in addition to commonly used types, also supports Stringset storage
When the data is written, remember to call Editor.commit ()
3. For sharedpreferences data read, the following example shows how to read an int type from the Preferences object, named index
of data
SharedPreferences preferences= getActivity().getPreferences(Context.MODE_PRIVATE);int0;intindex = preferences.getInt("index", defaultIndex);
- The first parameter of the Preferences.getint method is the key name of the value that you want to get, and the second parameter is the default value when the "index" parameter does not have a corresponding value
Extended Reading
- Save the file
Android Basics (14)