【发布时间】:2016-06-13 08:01:40
【问题描述】:
我只是想将用户从 editText 输入的内容存储在 Shared Preference 中,但它不起作用:
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”的日志,这是正常的,因为共享首选项中没有存储任何内容。
然后,我将某些内容存储在共享首选项中,并确保它已存储,我记录并获得我输入的内容的日志。 这意味着共享偏好数据已存储。
问题出在:我在共享偏好中存储了一些东西后,我去另一个活动,然后我回来了,所有存储在共享偏好中的数据都是GONE !
在浏览活动后,第一个日志仍然显示mDefault。
可能是什么问题?
编辑:
这是我的实例化:
onCreate:
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
【问题讨论】:
-
如何获得
keyword实例? -
@Codebender In
onCreate:keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences keywordEditor = keyword.edit(); -
@Codebender 我编辑了我的问题
-
@RuchirBaronia 我在其他答案中看到了您的消息,您必须设置首选项名称,才能在应用程序的任何位置设置和检索值。请参阅我的答案。
-
@RuchirBaronia 我刚刚重新创建了您的示例,似乎对我有用。如果不看更多代码,就很难解决这个问题。
标签: java android arrays database string