I am developing a dictionary app. In my app, I assume that user wants to save favourite words. I have decided to use SharedPreferences to save these values (I am aware that SQLite and files are better but I am stuck to “SharedPreferences”, so keep on with it).
Here below is my code:
@Override
public void onClick(View v) {
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
{
SharedPreferences.Editor editor = faves.edit();
editor.putString("favourite", mSelectedDB + "::" + mCurrentWordId + "::" + mCurrentWord + ",");
editor.commit();
}
Log.i(CONTENT_TAG,"Favourite saved!");
Toast toast = Toast.makeText(ContentView.this, R.string.messageWordAddedToFarvourite, Toast.LENGTH_SHORT);
toast.show();
}
The problem is that it does not retain more than one favourite word. I mean only one favourite word is saved and when a new one is added, the previous is erased.
So, how can the above code be edited so that this problem is solved?
Can you guys there help? Thank you very much.
You can save multiple favorites in a single preference by adding numerous favorites in a single string, each favorite item separated by comma. Then you can use
convertStringToArraymethod to convert it into String Array. Here is the full source code.Use MyUtility Methods to save multiple favorite items.
get String array of all favorites saved
Save these methods in separate Utility class
If you have to add extra favorites. Then get favorite string from
SharedPreferenceand append comma+favorite item and save it back intoSharedPreference.* You can use any other string for separator instead of comma.