I use the following code to save words to History in my dictionary app:
@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();
}
}
}
Everything is working fine with History.
Now I want to adapt this code to save favourite words. Almost every code lines are the same, the only difference is that the adapted code (without onPause()
) is placed under:
btnAddFavourite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
//The code is here...
}
But it is not working and the favourite words are not saved as in the case of History.
Can you guys there help? Thank you very much.