Android local storage solution SharedPreferences
Original article address
Storage location
The SharedPreferences data is stored in:/Data/ /Shared_prefs Directory, saved in XML format, the root element is:. The file name is the parameter value passed when obtaining the SharedPreferences instance.
value
Get instance
SharePerferences is an interface. Context implements the API: getSharedPreferences (String, int). This API returns a SharePerferences instance based on the String. The SharePerferences instances returned by the same String are the same. Strign specifies the name of the xml file that stores data.
Activity implements getPreferences (int). By default, the class name of Activity is used as the String to call getSharedPreferences (String, int ).
// Specify that the SharedPreferences data can only be read and written by this application. Context. MODE_PRIVATE // specify that the SharedPreferences data can also be read by other applications, but cannot be written. Context. MODE_WORLD_READABLE // specify that the SharedPreferences data can also be read and written by other applications. Context. MODE_WORLD_WRITEABLE // check whether the file exists. If so, append the file. Otherwise, create Context. MODE_WORLD_APPEND.
Read
// Determine whether SharedPreferences contains data of a specific key. Boolean contains (String key) // obtain all key-value pairs in SharedPreferences. Map
GetAll () // obtain the value corresponding to the specified key. If the key does not exist, the default value defValue is returned. Xxx getXxx (String key, Xxx defValue)
Write
The SharedPreferences interface does not provide the ability to write data, but uses its internal interface. You can call the SharedPreferences. edit () method to obtain the corresponding SharedPreferences. Editor object. Editor can write data to SharedPreferences as follows:
// Clear all data in SharedPreferences. Editor. clear () // store the data of the specified key to SharedPreferences. Editor. putXxx (String key, Xxx Value) // Delete the data item corresponding to the specified key in SharedPreferences. Editor. remove (String key) // when the Editor is edited, call this method to submit the modification. Boolean Editor. commit ()
Read and Write SharedPreferences of other applications
1. Create the corresponding Context of other applications.
Context useContext =createPackageContext("package_name",Context.CONTEXT_IGNORE_SECURITY);
2. Call the getSharedPreferences () method of the Context of other applications to obtain the SharedPreferences object.
3. Call the SharedPreferences. edit () method of other applications to obtain the corresponding SharedPreferences. Editor object.