问题描述
- 从不同的 activity 中访问 SharedPreferences
-
在第一个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, ""));
解决方案二:
用下面的代码从不同的程序中获取优先值
Context launcherContext = null;
try {
final int flags = Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE;
launcherContext = getApplicationContext().createPackageContext("com.another.package", flags);
} catch (final NameNotFoundException e) {
return ;
}
final SharedPreferences pref = launcherContext.getSharedPreferences(
"prefname",
Context.MODE_WORLD_READABLE | Context.MODE_MULTI_PROCESS);
final String prefValue = pref.getString("prefname", null);
Log.i("test", prefValue);
时间: 2024-11-01 05:10:46