我在listview项目中有一个listview和一个按钮,当按下时,通过将列表项转换为JSON,将partucular listitem添加到我的共享首选项中。 一切正常但我想限制添加到共享偏好的列表项目的数量说只有5个列表项目被添加到共享首选项中,如果添加了第6个列表项目,它应该替换已添加的第1个列表项目。
这可能吗?
这是我的sharedpreference.java
public class SharedPreference
{
public static final String PREFS_NAME = "MY__APP"
public static final String FAVORITES = "app_Favorite";
public SharedPreference(){
super();
}
public void saveFavorites(Context context, List<CodeList> favorites){
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, CodeList code){
List<CodeList> favorites = getFavorites(context);
if(favorites == null)
favorites = new ArrayList<CodeList>();
favorites.add(code);
saveFavorites(context,favorites);
}
public void removeFavorite(Context context, CodeList code) {
ArrayList<CodeList> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(code);
saveFavorites(context, favorites);
}
}
public ArrayList<CodeList> getFavorites(Context context) {
SharedPreferences settings;
List<CodeList> favorites;
//ArrayList<CodeList> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CodeList[] favoriteItems = gson.fromJson(jsonFavorites,
CodeList[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CodeList>(favorites);
//favorites = new ArrayList<CodeList>();
//favorites.addAll(Arrays.asList(favoriteItems));
} else
return null;
return (ArrayList<CodeList>) favorites;
//return favorites;
}
}