csh_34
csh_34
2013-03-25 02:30
采纳率: 80.4%
浏览 5.6k

从不同的 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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • nana4ever
    nana4ever 2013-03-25 05:57
    已采纳

    在另一个 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, ""));
    
    点赞 评论
  • CSDN_Ask
    问答小助手 2013-04-02 07:03

    用下面的代码从不同的程序中获取优先值

     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);
    
    点赞 评论

相关推荐