SharedPreferences 中支援的資料型別

SharedPreferences 允許你僅儲存原始資料型別(booleanfloatlongintStringstring set)。你不能在 SharedPreferences 中儲存更復雜的物件,因此它實際上是一個儲存使用者設定或類似設定的地方,它並不意味著是一個儲存使用者資料的資料庫(比如儲存一個使用者做的待辦事項列表)。

要在 SharedPreferences 中儲存內容,請使用 Key 和 Value。關鍵是如何引用以後儲存的內容以及要儲存的值資料。

    String keyToUseToFindLater = "High Score";
    int newHighScore = 12938;
    //getting SharedPreferences & Editor objects 
    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    //saving an int in the SharedPreferences file
    editor.putInt(keyToUseToFindLater, newHighScore);
    editor.commit();