从SharedPreference列表中删除项目[android]

时间:2014-06-10 02:01:28

标签: java android arraylist sharedpreferences

我想删除列表中的已检查元素,但不仅要从主应用程序中删除,还要从SharedPreferences中删除。现在,在我的应用程序中,我可以删除chcecked元素,但不能从SharedPreferences中删除,所以如果我回到我的活动,所有删除的元素仍然可见。求你帮帮我。

这是我的活动:

    SharedPreferences preferences;
    ArrayList<Object> list = new ArrayList<Object>();
    ArrayAdapter<Object> adapter;
    List<String> localization;
    Button btnDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moje_miejsca);

        btnDelete = (Button) findViewById(R.id.btnDelete);
        adapter = new ArrayAdapter<>(this,  android.R.layout.simple_list_item_multiple_choice, list);
        preferences = getSharedPreferences("coordinates", Activity.MODE_PRIVATE);

        Set<String> localizationSet = preferences.getStringSet("localization_set", new HashSet<String>());
        localization = new ArrayList<>(localizationSet);

        for (String listPosition : localizationSet) {
            list.add(listPosition);
            adapter.notifyDataSetChanged();
        }

        setListAdapter(adapter);


public void onClickBtnDelete(View view){

    SharedPreferences.Editor editor = preferences.edit();
    SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
    int itemCount = getListView().getCount();

    for(int i = itemCount-1; i >= 0; i--){

        if(checkedItemPositions.get(i)){
            int position = i + 1;
            adapter.remove(list.get(i));    

        }
    }

    editor.remove("localization_set").commit();
    itemCount = getListView().getCount();

    checkedItemPositions.clear();
    adapter.notifyDataSetChanged();

    for (int i = itemCount-1; i >= 0; i--){

        localization.add((String) list.get(i));
        setLocalization = new HashSet<String>(localization);
        editor.putStringSet("localization_set", setLocalization).commit();

    }

}

}

2 个答案:

答案 0 :(得分:12)

要删除特定保存的首选项,请使用

SharedPreferences.Editor editor = settings.edit();
editor.remove("tag_to_delete");
editor.commit();

要删除所有已保存的偏好设置,请使用此

SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();

答案 1 :(得分:0)

我发现了一个问题。这是我的错。我忘记了清单,这就是为什么列表会复制自己。它足以添加一个localization.clear()方法来解决这个问题