Loading...

Android Fragment及Activity 中使用sharedpreferences

Temperature: 0 °C

Mark ChangMark Chang
author_tools

在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", "..."));

以上紀錄~

https://innstory.com/story-Android_Fragment及Activity_中使用sharedpreferences-1867
Android

Prev
 利用_htaccess_限制可瀏覽ip來源

Next
使用jquery判斷上傳檔案大小 

About the Author

Mark Chang

離不開電腦的宅男

Visitor message

Leave some footprints to prove that you visited me

Recommended reading

Author's other related stories

php檢查陣列中大於0的值

php檢查陣列中大於0的值

假設有一個陣列$a $a = array(,,,,,,); 取得大於的數值有幾個 $tempa = ...

使用手機將網址分享到 Line時,如何強制使用預設(外部)瀏覽器開啟?

使用手機將網址分享到 Lin...

如標題,當厭惡了每次在line上面分享demo網址給客戶時點選網址就會使用line的瀏覽器開啟。 還...

Format JavaScript Date to yyyy-mm-dd

Format JavaScr...

timecalendar5 JavaScript將Sun May ,轉換成yyyymmdd func...

Please select an option

error

Hi, thank you for your participation, but you cannot vote repeatedly~

Join innstory now and start recording your story.

"Innstory" is a place to store stories. We are committed to becoming a warm platform. Deepening the bonds between people is our direction.
We are convinced that the blockchain between people is not just a cold calculation. Join us now.

Wrong format