一、作用
主要用於存放軟體的配置參數等資訊。sharedPreferences用於存取和修改軟體配置參數資料的介面,由getSharedPreferences(String, int)函數返回。任何具體的參數,都有一個單獨的該類執行個體向所有用戶端共用。修改參數必須通過SharedPreferences.Editor 對象,以確保這些參數在被提交到外存的時候它們的值處於一致的狀態和控制之下。該類暫不支援多進程操作,但是以後將提供該功能。
原文:
Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage.
Note: currently this class does not support use across multiple processes. This will be added later.
二、SharedPreferences.Editor 類簡介
public abstract SharedPreferences.Editor edit ()
Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
Note that you must call commit() to have any changes you perform in the Editor actually show up in the SharedPreferences.
三、存放參數執行個體源碼:
@Override
public void onClick(View v)
{
String name = nameText.getText().toString();
String age = ageText.getText().toString();
SharedPreferences preferences = getSharedPreferences("itcast",
Context.MODE_WORLD_READABLE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.putInt("age", new Integer(age));
editor.commit();
Toast.makeText(MainActivity.this, R.string.success, 1).show();
}
四、讀取參數執行個體源碼:
@Override
public void onClick(View v)
{
SharedPreferences preferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
String name = preferences.getString("name", "");
int age = preferences.getInt("age", 20);
nameText.setText(name);
ageText.setText(String.valueOf(age));
}
五、歸納
通過以上類的介紹和執行個體源碼分析,可以總結出一般步驟:
存放:
1.獲得SharedPreferences 的執行個體對象,通過getSharedPreferences()傳遞檔案名稱和模式;
2.獲得Editor 的執行個體對象,通過SharedPreferences 的執行個體對象的edit()方法;
3.存入資料,利用Editor 對象的putXXX()方法;
4.提交修改的資料,利用Editor 對象的commit()方法。
讀取:
1.獲得SharedPreferences 的執行個體對象,通過getSharedPreferences()傳遞檔案名稱和模式;
2.讀取資料,通過SharedPreferences 的執行個體對象的getXXX()方法。