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

使用CSS 讓ul li 橫向水平

使用CSS 讓ul li 橫...

好吧,其實這個css常在用,但我每次都沒特別紀錄,然後每次又忘記然後又要Google。 其實主要就是...

.htaccess設定網站預設首頁次序

.htaccess設定網站預...

一般php空間預設設定是index.php為首頁。 所以如果網站用index.php做首頁,就不需要...

當XAMPP遇到VMWARE占用PORT 443導致無法啟動APACHE

當XAMPP遇到VMWARE...

在使用XAMPP時,若系統有安裝 VMWare Workstation,VMWare會將 port ...

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