資料載入中

胡言亂語

Android Fragment及Activity 中使用sharedpreferences

在Android下想要儲存執行資料的方式有好幾種,例如存在手機空間或者是資料庫空間。

這裡紀錄一下使用sharedpreferences的方式。

若是使用Activity方式如下:

儲存
String msg = "test";
SharedPreferences sharedPreferences = getSharedPreferences("data" , MODE_PRIVATE);
//取得SharedPreferences , 丟入的參數為("名稱" , 存取權限)
sharedPreferences.edit().putString("MSG" , msg).apply();

取回
SharedPreferences sharedPreferences = getSharedPreferences("data" , MODE_PRIVATE);
//取出資料, 丟入的參數為(key , 若是沒值,預設為多少)
showBMI.setText("上回儲存結果:" + "\r\n\n" + sharedPreferences.getString("MSG" , "..."));

若是使用Fragment方式如下:

儲存
String msg = "test";
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putString("MSG" , msg);
edt.commit();

取回
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
showBMI.setText("上回儲存結果:" + "\r\n\n" + pref.getString("MSG", "..."));

以上紀錄~

  • Android儲存執行資料的方式
  • 使用sharedpreferences儲存資料
  • 在Activity中使用sharedpreferences
  • 在Fragment中使用sharedpreferences
  • 手機空間與資料庫空間的比較
https://innstory.com/story-AndroidFragment及Activity中使用sharedpreferences-1867

上一篇
 利用htaccess限制可瀏覽ip來源

下一篇
使用jquery判斷上傳檔案大小 

發表留言

作者簡介

離不開電腦的宅男


推薦閱讀

作者其他相關類別故事

PHPimplode 將陣列轉成字串

PHPimplode 將陣列…

Mark Chang 8 年又 41 天 2.2K

使用implode將陣列轉換成字串; 輸出結果: a,b,c,d,e

判斷字串是否存在於內容中

判斷字串是否存在於內容中

Mark Chang 7 年又 287 天 1.7K

以下範例~ 搜尋 If you are lucky enough to be different...

改變input placeholder 字體顏色

改變input placeh…

Mark Chang 7 年又 275 天 2.5K

通常我們會使用 placeholder 來作為欄位提醒文字~ 通常 placeholder 字體...