一般來說,要將資料存放在手機裡,有幾個方法,如輸出到檔案,資料庫(SQL),或是Preference。
我們今天來看如何將值存放至Preference:
儲存:
// 取得Preference
SharedPreferences sp;
sp = getPreferences(MODE_PRIVATE);
// 取得用來編輯的Editor
Editor editor = sp.edit();
// 利用put方法設定Key and value
editor.putBoolean("key_boolean", true);
editor.putString("key_string", "aaa");
editor.putFloat("key_float", 0.01F);
editor.putInt("key_int", 8888);
editor.putLong("key_long", 1234L);
// 儲存
editor.commit();
取得儲存的值:
// 取得Preference
SharedPreferences sp;
sp = getPreferences(MODE_PRIVATE);
// 根據不同的型別,使用不同的get方法
// 第二個參數是用來,當讀取的KEY值不在時,指定要回傳的預值即寫在這裡
boolean m_boolean = sp.getBoolean("key_boolean", false);
String m_string = sp.getString("key_string", "");
float m_float = sp.getFloat("key_float", 0);
int m_int = sp.getInt("key_int", 0);
long m_long = sp.getLong("key_long", 0);
補充:
getPreferences方法的第二個參數,可以設定資料存取的權限
常數
|
描述
|
MODE_PRIVATE
|
私有的,其它應用程式無法使用
|
MODE_WORLD_READABLE
|
其它應用程式可以讀取
|
MODE_WORLD_WRITABLE
|
其它應用程式可以寫入
|
下面是一個完整例子
http://pianovv510.blogspot.tw/2013/04/andriod-sharedpreferences.html
沒有留言:
張貼留言