共享偏好不适用于两个活动?

时间:2014-08-09 21:10:10

标签: android sharedpreferences

从文件Login.java写入首选项:

SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(Login.this);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("username", username);
                    edit.commit();

在UpdateList.java中加载首选项:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(UpdateList.this);
           String post_username = sp.getString("username", "anon");

我想通过json将此共享首选项传递给php文件,但它无法在两个活动中保存首选项

1 个答案:

答案 0 :(得分:0)

尝试使用此代码访问和编写共享首选项

public static final String PREF_FIELD = "name";
    public String getText(Context context) {
            SharedPreferences preferences = context.getSharedPreferences(
                    "GLOBAL",
                    Context.MODE_PRIVATE);
            String sessionId = preferences.getString(
                    PREF_FIELD,
                    "");
            return sessionId;
        }

        public void setText(Context context, String text) {
            SharedPreferences preferences = context.getSharedPreferences(
                    "GLOBAL",
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(PREF_FIELD, text);
            editor.commit();
        }