I'm not so sure on how can I store more than one value in shared preferences on an Android app using the same key.
What the app do is show a list and a button to add that item to favorites I want to store that numeric value to preferences and when the user go to the favorite list send all the stored favorites through http post in an array.
EDIT: I'm doing it this way but when I add a new value it overrides the last one, check implode method, I add the new value to the stored list empty or not it has to add the new value and preserve the last ones.
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class FavoriteActivity {
private static String FAVORITE_LIST = "FAV_LIST";
private static SharedPreferences sharedPreference;
private static Editor sharedPrefEditor;
public static List<NameValuePair> getFavoriteList(Context context) {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(context);
}
String storedList = sharedPreference.getString(FAVORITE_LIST, "");
return explode(storedList);
}
public static void saveFavorite(String fav, Context context) {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(context);
}
sharedPrefEditor = sharedPreference.edit();
implode(getFavoriteList(context), fav, 1);
sharedPrefEditor.putString(FAVORITE_LIST, fav);
sharedPrefEditor.commit();
}
public static List<NameValuePair> explode(String string) {
StringTokenizer st = new StringTokenizer(string, ",");
List<NameValuePair> v = new ArrayList<NameValuePair>();
for (; st.hasMoreTokens();) {
v.add(new BasicNameValuePair("id[]", st.nextToken()));
}
return v;
}
public static String implode(List<NameValuePair> list, String value,
int mode) {
StringBuffer out = new StringBuffer();
switch (mode) {
case 0:
list.remove(new BasicNameValuePair("id[]", value));
break;
case 1:
list.add(new BasicNameValuePair("id[]", value));
break;
}
boolean first = true;
for (NameValuePair v : list) {
if (first)
first = false;
else
out.append(",");
out.append(v.getValue());
}
return out.toString();
}
}