Steps for usage:
1. Get the SharedPreferences object
2. Call the edit() method of the SharedPreferences object to obtain a SharedPreferences.Editor object.
3. Store key-value key-value pair data to the SharedPreferences.Editor object.
4. Call the commit method to submit the added data.
Detailed process:
1. Get the SharedPreferences object
2. Call the edit() method of the SharedPreferences object to obtain a SharedPreferences.Editor object.
SharedPreferences.Editor editor = getSharedPreferences(“data”,MODE_PRIVATE).edit();
3. Add data to the SharedPreferences.Editor object.
editor.putString("name","Lily"); //Store as a key-value pair
editor.putInt("age","20"); //Store as a key-value pair
editor.putBoolean("married",false); //Store as a key-value pair
4. Call the commit method to submit the added data.
editor.commit();
At the same time, there are two commonly used methods of Edit:
editor.remove(String key) : The key-value pair corresponding to the key will be removed in the next commit
editor.clear(): remove all key-value pairs
There are two ways to get SharedPreferences:
1 Call the getSharedPreferences() method of the Context object
2 Call the getPreferences() method of the Activity object
The difference between the two ways:
The SharedPreferences object obtained by calling the getSharedPreferences() method of the Context object can be shared by other
components .
The SharedPreferences object obtained by calling the getPreferences() method of the Activity object can only be used in this Activity.
SharedPreferences的四种操作模式:
Context.MODE_PRIVATE
Context.MODE_WORLD_READABLE
Context.MODE_WORLD_WRITEABLE
Context.MODE_APPEND/Context.MODE_MULTI_PROCESS
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入.
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.
Context.MODE_MULTI_PROCESS:sdk2.3后添加的选项,当多个进程同时读写同一个SharedPreferences时它会检查文件是否修改。
将数据保存至SharedPreferences:
SharedPreferences preferences=getSharedPreferences("user",Context.MODE_PRIVATE);
Editor editor=preferences.edit();
String name="xixi";
String age="22";
editor.putString("name", name);
editor.putString("age", age);
editor.commit();
从SharedPreferences获取数据:
SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
String name=preferences.getString("name", "defaultname");
String age=preferences.getString("age", "0");