csh_34
csh_34
采纳率80.4%
2013-03-25 02:30

从不同的 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 8年前

    在另一个 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, ""));
    
    点赞 2 评论 复制链接分享
  • CSDN_Ask 问答小助手 8年前

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

     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);
    
    点赞 评论 复制链接分享

相关推荐