片段中的共享首选项 [英] sharedPreferences in Fragment
问题描述
我知道以前有人问过这个问题,但我似乎无法弄清楚
I know this has been asked before, but i can't seem to figure it out
我正在尝试通过以下方式获得我的偏好:
i am trying to get my preferences by this:
SharedPreferences preferences = this.getActivity().getSharedPreferences("storedName", Context.MODE_PRIVATE);
String loginemail = preferences.getString("storedName", "");
但这似乎不起作用,我有多个 sharedPreferences 需要在我的片段中获取它们的正确方法是什么?由于 getDefaulSharedPreferences(this)
不起作用.
but this doesn't seem to work, i have multiple sharedPreferences which i need to get in my fragment what is the correct way to do it?
As getDefaulSharedPreferences(this)
doesn't work.
我像这样存储我的首选项:
i store my prefs like so:
savePreferences("shareUniqePass", uniqePassIds.getText().toString());
savePreferences("storedName", inputEmail.getText().toString());
savePreferences("Storedpass", inputPassword.getText().toString());
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor checkbox = sharedPreferences.edit();
checkbox.putBoolean(key, value);
checkbox.commit();
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor names = sharedPreferences.edit();
names.putString(key, value);
names.commit();
}
推荐答案
不要从 getSharedPreferences
获取,而是使用 getDefaultSharedPreferences
.
Instead of getting it from getSharedPreferences
use the getDefaultSharedPreferences
.
As getDefaulSharedPreferences(this) doesn't work.
您使用 getDefaultSharedPreferences
来保存数据,因此您必须使用 getDefaultSharedPreferences
来获取保存的数据.
You used getDefaultSharedPreferences
for saving the data and therefore you must use getDefaultSharedPreferences
to get the data that was saved.
this
表示您的片段实例,而不是使用 getActivity()
从您的活动中获取上下文实例.
this
mean the instance of your fragment instead use the getActivity()
to get the instance of context from your activity.
示例:
String loginemail = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString(PREF_USER_NAME, "");;
这篇关于片段中的共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!