App需要保存搜索历史记录,首先想到的就是利用SharedPreferences保存set,因为每条记录都是一个String。(当然也可以用数据库,略显麻烦一点)
在追加搜索记录时出现失败,总是只有一条记录。代码如下:
//错误实例
//将保存的set取出
Set<String> set = SPUtil.getSet(Constants.SEARCH_HISTORY);
//添加新数据
set.add(data);
//重新保存
SPUtil.saveSet(Constants.SEARCH_HISTORY,set);
修改后代码:
//将保存的set取出
Set<String> set = SPUtil.getSet(Constants.SEARCH_HISTORY);
//将取出的set作为参数进行重构(解决问题的关键)
set = new HashSet<>(set);
//添加新数据
set.add(data);
//重新保存
SPUtil.saveSet(Constants.SEARCH_HISTORY,set);
SPUtil工具类
public class SPUtil {
private static Context context = MyApp.context;
private static SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
public static void save(String key, String value) {
sp.edit().putString(key, value).apply();
}
public static void save(String key, boolean value) {
sp.edit().putBoolean(key, value).apply();
public static void saveInt(String key, int value) {
sp.edit().putInt(key, value).apply();
}
public static void saveSet(String key, Set<String> set){
sp.edit().putStringSet(key,set).apply();
}
public static Set<String> getSet(String key){
return sp.getStringSet(key,new HashSet<String>());
}
public static String get(String key, String defaultValue) {
return sp.getString(key, defaultValue);
}
public static String getString(String key) {
return sp.getString(key, "");
public static int getInt(String key) {
return sp.getInt(key, 0);
}
public static boolean getBoolean(String key) {
return sp.getBoolean(key, false);
}
public static boolean getBoolean(String key,boolean def) {
return sp.getBoolean(key, def);
}
}