【发布时间】:2012-01-30 09:58:03
【问题描述】:
我使用以下代码将单词保存到我的字典应用中的历史记录:
@Override
public void onPause()
{
super.onPause();
saveHistoryToPreferences();
}
public void saveHistoryToPreferences()
{
if (prefs.getBoolean("saveHistory", true) && mWordHistory != null && mWordHistory.size() >= 1)
{
StringBuilder sbHistory = new StringBuilder();
for (String item : mWordHistory)
{
sbHistory.append(item);
sbHistory.append(",");
}
String strHistory = sbHistory.substring(0, sbHistory.length()-1);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("history", strHistory);
editor.commit();
//Log.i(CONTENT_TAG,"history = " + strHistory);
Log.i(CONTENT_TAG,"History saved!");
}
}
public void loadHistoryFromPreferences()
{
if (prefs.getBoolean("saveHistory", true))
{
String strHistory = prefs.getString("history", "");
Log.i(CONTENT_TAG, "History loaded");
if (strHistory != null && !strHistory.equals(""))
{
mWordHistory = new ArrayList<String>(Arrays.asList(strHistory.split(",")));
}
else
{
if (mWordHistory == null)
{
mWordHistory = new ArrayList<String>();
}
else
{
mWordHistory.clear();
}
}
}
else
{
if (mWordHistory == null)
{
mWordHistory = new ArrayList<String>();
}
else
{
mWordHistory.clear();
}
}
}
History 一切正常。
现在我想修改这段代码来保存最喜欢的单词。几乎每一行代码都是一样的,唯一的区别是改编后的代码(不带onPause())放在:
btnAddFavourite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
//The code is here...
}
但它不起作用,并且喜欢的单词没有像历史一样保存。
你们能帮忙吗?非常感谢。
【问题讨论】:
标签: java android sharedpreferences