从文件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文件,但它无法在两个活动中保存首选项
答案 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();
}