Android資料存放區方式之:SharePreference
做開發肯定離不了資料,因為編程=演算法+資料。做Android應用開發常用到的資料存放區方式有以下五種:
1 ,使用SharedPreferences儲存資料 2, 檔案儲存體資料 3 ,SQLite資料庫儲存資料 4 ,使用ContentProvider儲存資料 5, 網路儲存資料 今天就簡單介紹下第一種儲存方式:使用SharedPreferences儲存資料。 ---------------------------使用SharedPreferences儲存資料-----------------------------------------------------
SharePreference 是一個輕量級的儲存機制。只能儲存一些基礎類型,以xml檔案為載體。檔案存放路徑為data/data/包名/share_prefs/檔案名稱.xml儲存的時候類似於Map,key-Value值對。存放資料的時候需要調用到SharePreference介面的一個editor屬性,通過editor進行資料添加,移除等操作資料,而且必須調用editor的commit方法。
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:id="@+id/input_edt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="請輸入儲存內容" />
android:id="@+id/save_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="儲存資料" />
----------------存取資料操作----------------------------------
public class MainActivity extends Activity implements OnClickListener {
/**內容輸入框 */
private EditText inputEdt;
/**儲存按鈕 */
private Button saveBtn;
/**SharedPreferences*/
private SharedPreferences mSharedPreferences;
/**Editor*/
private Editor mEditor;
private static final String SAVE_FILE_NAME = "save_spref";
private static final String SAVE_FILE_KEY = "save_key";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
mSharedPreferences = getSharedPreferences(SAVE_FILE_NAME, MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
/**如果要取得對應的值*/
String getContent = mSharedPreferences.getString(SAVE_FILE_KEY, "");
inputEdt.setText(getContent);
}
private void findViewsById() {
inputEdt = (EditText) findViewById(R.id.input_edt);
saveBtn = (Button) findViewById(R.id.save_btn);
saveBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.save_btn) {
String content = inputEdt.getText().toString();
mEditor.putString(SAVE_FILE_KEY, content);
}
}
/**
* mSharedPreferences=getSharedPreferences(SAVE_FILE_NAME, MODE_PRIVATE);//
方法的第一個參數用於指定該檔案的名稱,名稱不用帶尾碼,尾碼會由Android自動加上;
方法的第二個參數指定檔案的操作模式,共有四種操作模式。
四種操作模式分別為:
1. MODE_APPEND: 追加方式儲存
2. MODE_PRIVATE: 私人方式儲存,其他應用無法訪問
3. MODE_WORLD_READABLE: 表示當前檔案可以被其他應用讀取
4. MODE_WORLD_WRITEABLE: 表示當前檔案可以被其他應用寫入
*/
}