[Android]使用SharedPreferences儲存使用者設定資料

運用SharedPreferences可以儲存使用者輸入的資料,然後可於下次啟動APP時,讀取上次儲存的值,避免使用者重複輸入的困擾。

那何時讀取資料?何時儲存資料?我們要瞭解Activity的生命週期。一個Activity就是APP的一個畫面,當畫面切換時,表示切換到另一個Activity。
因此,我們要在Activity被產生時,載入先前儲存的資料,即在 onCreate() 中載入。
而我們要在切換到另一個畫面時儲存資料,即在 onPause() Funtion中進行儲存。

接著看程式碼如何撰寫。

載入說明:
在onCreate function加入載入的程式碼restorePrefs()這個function,然後運用SharedPreferences類別,取得手機中的設定檔PREF,再利用getString方法取得特定的設定值,然後將值給予指定的欄位,例如:edit_text_height.setText();

public static final String PREF = "BMI_PREF";
public static final String PREF_HEIGHT = "BMI_Height";

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        restorePrefs();
        setListeners();
}

//Restore preferences
private void restorePrefs(){
SharedPreferences settings = getSharedPreferences(PREF,0);
String pref_height = settings.getString(PREF_HEIGHT, "");
if(! "".equals(pref_height)){
edit_text_height.setText(pref_height);
edit_text_weight.requestFocus();
}
}


儲存說明:
在onPause function加入儲存的程式碼,產生SharedPreferences類別,將值存到手機中的設定檔PREF,利用edit().putString將值寫到指定的欄位PREF_HEIGHT,然後再透過.commit()完成儲存。

@Override
protected void onPause() {
super.onPause();
//save user preferences
SharedPreferences settings = getSharedPreferences(PREF, 0);
settings.edit()
.putString(PREF_HEIGHT, edit_text_height.getText().toString())
.commit();
}
如果你對旅行有興趣,歡迎來我們FB的旅遊粉絲頁看看吧
https://www.facebook.com/Lupin33RoundTheWorld

沒有留言:

張貼留言