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.
SharedPreferences are not intended to store a lot of data, there is no limit per se (since it is an xml file), but for larger sets of data, I would suggest using Room (or SQLite for the older projects).
You can save String and custom array list using Gson library. =>First you need to create function to save array list to SharedPreferences. public void saveListInLocal(ArrayList<String> list, String key) { SharedPreferences prefs = getSharedPreferences("AppName", Context. MODE_PRIVATE); SharedPreferences.
Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
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 convertStringToArray
method to convert it into String Array. Here is the full source code.
Use MyUtility Methods to save multiple favorite items.
MyUtility.addFavoriteItem(this, "Sports");
MyUtility.addFavoriteItem(this, "Entertainment");
get String array of all favorites saved
String[] favorites = MyUtility.getFavoriteList(this);// returns {"Sports","Entertainment"};
Save these methods in separate Utility class
public abstract class MyUtility {
public static boolean addFavoriteItem(Activity activity,String favoriteItem){
//Get previous favorite items
String favoriteList = getStringFromPreferences(activity,null,"favorites");
// Append new Favorite item
if(favoriteList!=null){
favoriteList = favoriteList+","+favoriteItem;
}else{
favoriteList = favoriteItem;
}
// Save in Shared Preferences
return putStringInPreferences(activity,favoriteList,"favorites");
}
public static String[] getFavoriteList(Activity activity){
String favoriteList = getStringFromPreferences(activity,null,"favorites");
return convertStringToArray(favoriteList);
}
private static boolean putStringInPreferences(Activity activity,String nick,String key){
SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, nick);
editor.commit();
return true;
}
private static String getStringFromPreferences(Activity activity,String defaultValue,String key){
SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
String temp = sharedPreferences.getString(key, defaultValue);
return temp;
}
private static String[] convertStringToArray(String str){
String[] arr = str.split(",");
return arr;
}
}
If you have to add extra favorites. Then get favorite string from SharedPreference
and append comma+favorite item and save it back into SharedPreference
.
* You can use any other string for separator instead of comma.
SharedPreferences
work via simple key/value so when you provide a new value for the same key, the previous value is overwritten. The only way to do what you're trying to do is to use different keys, which sort of hints towards the fact that you probably shouldn't be using SharedPreferences
for what you're trying to do.
Honeycomb added the putStringSet
method, so you could use that if you don't have to support anything less than Honeycomb:
@Override
public void onClick(View v) {
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
{
Set<String> faveSet = faves.getStringSet("favourite");
faveSet.add(mSelectedDB + "::" + mCurrentWordId + "::" + mCurrentWord + ",");
SharedPreferences.Editor editor = faves.edit();
editor.putStringSet("favourite", faveSet);
editor.commit();
}
Log.i(CONTENT_TAG,"Favourite saved!");
Toast toast = Toast.makeText(ContentView.this, R.string.messageWordAddedToFarvourite, Toast.LENGTH_SHORT);
toast.show();
}
If you need support for pre-Honeycomb devices, you will have to come up with your own scheme.
One possibility is to store the words as comma-separated values in one preference.
Another is to generate a new key for each new word, "favourite1", "favourite2", "favourite3" and have another preference you use to store the number of words.
Every time you click the button you save the favorite word with the already present key: favorite
and you override it. To save more than one word you have to save the words with different keys.
So every time you save a favorite word you could do:
private static int incrementedValue = 0;
...
@Override
public void onClick(View v) {
SharedPreferences faves = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = faves.edit();
editor.putString("favourite" + incrementedValue, 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();
incrementedValue++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With