在第一個activity (MainActivity)中,我通過 SharedPreferences 保存數據:
Editor editor = mGameSettings.edit();
editor.putString(GAME_PREFERENCES_SHOP, Shops.get(lv.getCheckedItemPosition()));
editor.commit();
當重啟程序後,我可以從MainActivity 中讀取這個數據:
if (mGameSettings.contains(GAME_PREFERENCES_SHOP))
Tv2.setText(mGameSettings.getString(GAME_PREFERENCES_SHOP, ""));
如何從其它的activity中讀取和編輯這個SharedPreferences?
在另一個 activity 中添加下面的代碼:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (sp.contains(MainActivity.GAME_PREFERENCES_SHOP)) //hoping that GAME_PREFERENCES_SHOP is a static constant defined in MainActivity
Tv2.setText(sp.getString(MainActivity.GAME_PREFERENCES_SHOP, ""));