共享偏好? (非常简单的问题!?) [英] Shared preferences? (Extremely simple issue!?)
问题描述
我只是试图在共享偏好设置中存储来自editText的用户输入,但不起作用:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
}
return true;
});
当我第一次编辑文本时,我会先获取一个日志 mDefault
这是正常的,因为没有存储在共享首选项中。
When I first edit the text, I will first get a log of "mDefault
" which is normal, since nothing is stored in the shared preference.
然后,我在共享首选项中存储一些东西,肯定它存储,我日志,我得到一个日志,我打字。 这意味着存储了共享的首选项数据。
Then, I store something in the shared preference, and to make sure it stored, I log and I get a log of what I typed. Which means the shared preference data WAS stored.
遇到问题:喜欢,我去一个不同的活动,我回来,共享偏好中存储的所有数据 GONE!
Heres the problem: After I have stored something in the shared preference, I go to a different activity, and I come back, and all the data stored in the shared preference is GONE!
通过活动导航后,第一本日志仍然显示 mDefault
。
The very first log still says mDefault
after navigating through activities.
?
编辑:
以下是我的实例化:
onCreate
:
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
推荐答案
非常重要:需要偏好设置名称(例如:MY_PREFS_NAME)设置和检索值:
Very important: you need a Preference name (for example: "MY_PREFS_NAME") to set and retrieve the values:
SharedPreferences.Editor keywordEditor = context.getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
使用相同的常数首选项名称,它会在应用程序的任何一点给予相同的首选项。
Use the same constant Preference name and it will give you the same preferences in any point of your app.
这篇关于共享偏好? (非常简单的问题!?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!