我想保留"收藏夹"在SharedPreferences中记录,但出了点问题。在独立于此的SharedPreferences中,我正在做的事情总是有一条记录。第一个我决定添加。我正在检查,但是删除它效果很好,但在完成重新启动或重新安装应用程序后,问题又回来了。我添加3条记录,重新启动应用程序,首先我添加了。我删除它,添加另一个,重新启动应用程序,有午餐前的第一个。我删除它,重新启动应用程序,这个仍然存在。我删除它,添加另一个,重新启动应用程序,前一个在列表中。我试过了:
我的适配器,显示我要保留的一条记录:
public class DayFavouriteAdapter extends ArrayAdapter<String> {
private Context context;
private String[] values;
public DayFavouriteAdapter(Context context, String[] values) {
super(context, R.layout.day_favourite, values);
this.context = context;
this.values = values;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View day = inflater.inflate(R.layout.day_favourite, parent, false);
final SharedPreferences prefs = Data.getPreferences(context, null);
final Set<String> favs = prefs.getStringSet(Data.favourites, new HashSet<String>());
day.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final Activity activity = FavouriteActivity.getInstance();
AlertDialog.Builder deleting = new AlertDialog.Builder(activity);
deleting.setTitle("Deleting");
deleting.setMessage("Are you sure?");
deleting.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
boolean a = favs.remove(favs.toArray(new String[]{})[position]); //a is always true, misstake is impossible
Log.d("AC", favs.toString() + ""); //returns correct result
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(Data.favourites, favs);
editor.commit();
editor.apply();
Log.d("AC", prefs.getStringSet(Data.favourites, new HashSet<String>()) + ""); //returns correct result
activity.recreate(); //after this, everything is cool.
}
});
deleting.setNegativeButton("No", null);
deleting.show();
return false;
}
});
return day;
}
}
我的Data.java(如果需要):
public abstract class Data {
public static final String favourites = "favourites";
public static final SharedPreferences getPreferences(Context context, String s) {
if (s==null) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
return context.getSharedPreferences(s, Activity.MODE_PRIVATE);
}
}
我正在使用几种方法来做到这一点,但任何方法都有效。