【发布时间】:2015-01-20 13:50:30
【问题描述】:
我已经搜索过这个问题的解决方案,但我没有得到答案,但我不知道之前是否已经回答过。我在网上获得了一个代码,使用 Gson 库将对象保存为 SharedPreferences 中的 JSON 字符串,并对其进行了调整以供使用。
代码运行良好,除非我需要从 SharedPreferences 中删除项目。该项目不会删除。请帮我看看代码。代码粘贴如下。
对象类:
public class fPerson {
String name, id, type, cat;
public fPerson(String nm, String ID, String typ, String ct)
{
this.name = nm;
this.id = ID;
this.type = typ;
this.cat = ct;
}
public void setName(String n)
{
this.name = n;
}
public void setId(String i)
{
this.id = i;
}
public void settype(String ty)
{
this.type = ty;
}
public void setCat(String ct)
{
this.cat = ct;
}
public String getName()
{
return this.name;
}
public String getId()
{
return this.id;
}
public String getType()
{
return this.type;
}
public String getCat()
{
return this.cat;
}
public String toString()
{
return new String(getName() + " " + getId()+ " " + getType());
}
}
具有 SharedPreferences 的类
public class Preferences {
public static final String PREFS_NAME = "APP";
public static final String FAVORITES = "Favorite";
public Preferences() {
super();
}
public void saveFavorites(Context context, List<fPerson> 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, fPerson person) {
List<fPerson> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<fPerson>();
favorites.add(person);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, fPerson person) {
ArrayList<fPerson> favorites = getFavorites(context);
if (favorites != null) {
Iterator<fPerson> iter = favorites.listIterator();
while(iter.hasNext())
{
fPerson temp = (fPerson)iter.next();
if(temp.getId().equals(person.getId()))
{
favorites.remove(person);
break;
}
}
saveFavorites(context, favorites);
}
}
public ArrayList<fPerson> getFavorites(Context context) {
SharedPreferences settings;
List<fPerson> favorites;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
fPerson[] favoriteItems = gson.fromJson(jsonFavorites, fPerson[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<fPerson>(favorites);
} else
return null;
return (ArrayList<fPerson>) favorites;
}
}
【问题讨论】:
-
无法从首选项中删除数据,因为您使用相同的键来保存所有值并尝试使用值而不是键从首选项中删除项目。使用键 FAVORITES 删除值
-
感谢您的回复。我不是想从偏好中删除整个字符串。首选字符串是每个对象的 JSON 数组的字符串。我想要做的是从 JSON 数组中删除一个对象,并且应该留下一串 JSON 数组的剩余对象。
-
你在
editor.putString()之前尝试过editor.clear() -
@ja_mesa:谢谢。让我试试,然后给你反馈。
-
@ja_mesa:我试过了,没用
标签: android json sharedpreferences