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

錯誤訊息Division by zero的解決方式

錯誤訊息Division b...

錯誤訊息Division by zero發生的原因是因為除數是導致的錯誤: 解決方式如下: ) 運行...

想在網頁上預覽PDF可使用的方案

想在網頁上預覽PDF可使用的...

使用pdfobject.js #設定顯示位置 <div id="pdf"></d...

CSS3濾鏡Filter的十種特效

CSS3濾鏡Filter的十...

CSS 濾鏡效果 Filters 主要是運用在圖片上,以實現一些特效。 grayscale 灰階 s...

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