我不太确定如何使用相同的密钥在 Android 应用程序的共享首选项中存储多个值。
该应用程序所做的是显示一个列表和一个按钮以将该项目添加到收藏夹我想将该数值存储到首选项中,当用户转到收藏夹列表时,通过数组中的 http post 发送所有存储的收藏夹。
编辑:我是这样做的,但是当我添加一个新值时它会覆盖最后一个值,检查 implode 方法,我将新值添加到存储列表中为空,或者它必须添加新值并保留最后一个值.
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();
}
}