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 mb_substr() 函式,擷取部分字串並記得使用UTF-8。

使用PHP mb_subst...

pexelsphotohello5 文字長度太長,一般來說我們可以使用DIV包住字串,再定義DIV的...

fancybox close的方式

fancybox close...

parent.$.fancybox.close(); parent.jQuery.fancybox....

PHP使用array_product()函數求得陣列中的乘積

PHP使用array_pro...

arrayproduct()是PHP中的一個內建函數,可以返回陣列中所有元素的乘積。 例如 $arr...

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