不同於文件的存儲方式,SharedPreferences是使用鍵值對的額方式來存儲數據的。也就是說當保存一套數據的時候,需要給這條數據提供一個對應的鍵,這樣在讀取數據的時候就可以通過這個鍵把相應的值取出來。而且SharedPreferences還支持多種不同的數據類型存儲。存儲的數據和讀取的數據類型一致。
SharedPreferences的用法
Android提供了三種方法用於得到SharedPreferences對象。
1. Context類中的getSharedPreferences()方法
此方法接收兩個參數,第一個參數用於指定SharedPreferences文件的名稱,如果指定的文件不存在則會創建一個。SharedPreferences文件都是存放在/data/data/<packagename>/shared_prefs/目錄下的。第二個參數用於制定操作模式,主要有兩種模式可以選擇,默認的MODE_PRIVATE和MODE_MULTI_PROCESS,MODE_PRIVATE表示只有當前的應用程序纔可以對這個SharedPreferences文件進行讀寫。另一種模式則一般用於會有多個進程中對同一個SharedPreferences文件進行讀寫的情況。與文件存儲一樣有兩種操作模式被拋棄。
2. Activity類中的gerPreferences()方法
這個方法跟Contexet中的方法相類似,不同之處是該方法只接受一個操作模式作爲參數,因爲使用這個方法是會自動將當前活動的類名作爲SharedPreferences的文件名
3. PreferenceManager類中的gerDefaultSharedPreferences()方法,它只接受一個Context參數,並自動使用當前應用程序的報名作爲前綴來命名SharedPreferences文件。
得到SharedPreferences對象之後,就可以開始向文件中存儲數據了,存儲數據分爲三步
1. 調用SharedPreferences對象的edit()方法來獲取一個SharedPreferences.Editor對象。
2. 向SharedPreferences.Editor對象中用(put+數據類型)方法添加數據
3. 調用commit()方法將添加的數據提交,從而完成數據存儲操作。
同樣定義輸入框用來獲得將要寫入的數據和顯示數據的文本框,定義兩個按鈕來完成兩個讀寫兩個事件。
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="顯示讀取的數據"/>
<EditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="寫入數據"/>
<Button
android:id="@+id/button_write"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="寫入數據"/>
<Button
android:id="@+id/button_read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="讀取數據"/>
在MainActivity中添加兩個點擊事件完成讀寫操作
private void read() {
//SharedPreferences preferences=getSharedPreferences("content_prefs",MODE_PRIVATE);
SharedPreferences preferences=getPreferences(MODE_PRIVATE);
String data=preferences.getString("content","DefaultValue");
mEditText.setText("");
mTextView.setText(data);
}
private void write() {
//SharedPreferences preferences=getSharedPreferences("content_prefs",MODE_PRIVATE);//Context中的方法
SharedPreferences preferences=getPreferences(MODE_PRIVATE);//Activity中的方法
editor=preferences.edit();
editor.putString("content",mEditText.getText().toString());
editor.commit();
}
MainActivity那個文件就是使用的是Activity中的方法。