Scope of application : Save a small amount of data, and the format of this data is very simple: string type, value of basic type. For example, various configuration information of the application (such as whether to turn on the sound effect, whether to use the vibration effect, player points of the mini game, etc.), unlock password, etc.
Core principle : Save key-value key-value pair data based on XML file storage, which is usually used to store some simple configuration information. Through the File Explorer panel of DDMS, expand the file browsing tree, it is obvious that the SharedPreferences data is always stored in the /data/data/< package name >/shared_prefs directory. The SharedPreferences object itself can only obtain data and does not support storage and modification . The storage modification is implemented by the internal interface Editor object obtained by SharedPreferences.edit () . SharedPreferences itself is an interface. The program cannot directly create SharedPreferences instances. It can only obtain SharedPreferences instances through the get SharedPreferences (String name, int mode) method provided by Context . In this method, name indicates the name of the xml file to be operated. The second parameter details as follows:
Context.MODE_PRIVATE : Specifies that the SharedPreferences data can only be read and written by this application.
Context.MODE_WORLD_READABLE : Specifies that the SharedPreferences data can be read by other applications , but not written.
Context.MODE_WORLD_WRITEABLE : Specifies that the SharedPreferences data can be read and written by other applications
Editor has the following main important methods:
SharedPreferences.Editor clear(): Clear all data in SharedPreferences
SharedPreferences.Editor putXxx(String key, xxx value): Store the data corresponding to the specified key to SharedPreferences, where xxx can be boolean, float, int and other basic types of data
SharedPreferences.Editor remove(): Delete the data item corresponding to the specified key in SharedPreferences
boolean commit(): When the Editor is finished editing, use this method to submit the changes
class ViewOcl implements View.OnClickListener{ @Override public void onClick(View v) { switch(v.getId()){ case R.id.btnSet: String IP = txtCode.getText().toString().trim(); SharedPreferences.Editor editor = getSharedPreferences("IP_DATA", MODE_WORLD_WRITEABLE).edit(); editor.putString("IP", IP); editor.commit(); Toast.makeText(getApplicationContext(), "SUCCESS", Toast.LENGTH_LONG).show(); break; case R.id.btnGet: SharedPreferences read = getSharedPreferences("IP_DATA", MODE_WORLD_READABLE); String value = read.getString("IP", ""); Toast.makeText(getApplicationContext(), "IP:"+value, Toast.LENGTH_LONG).show(); break; } } }