删除 android 中的共享首选项

Delete Shared Preferences in android

这就是我添加共享首选项的方式

    ct = sp.getInt("count", 0);
    if (ct > 0) {
        for (int i = 0; i <= ct; i++) {
            list.add(sp.getString("Value[" + i + "]", ""));
        }
    }
        adp = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, list);
        Listtt.setAdapter(adp);
        btnad.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                sped.putString("Value[" + ct + "]", editText.getText().toString());
                sped.commit();
                list.add(sp.getString("Value[" + ct + "]", ""));
                ct += 1;
                sped.putInt("count", ct);
                adp.notifyDataSetChanged();

            }
        });

通过这个我可以成功删除 Sharedprefrences Value 并将其从列表中删除

 sp.edit().remove("key_to_remove").apply();
             adp.remove("name_to_rmv");
             adp.notifyDataSetChanged();

现在我的问题是它留下空白 space 当我调用它就像关闭 activity 并再次打开它时我删除的值有空白 space 。就像下图一样,我删除了“两个”,但是当我关闭并打开我的应用程序时,它给了我空白 space

我如何填充适配器

 ct = sp.getInt("count", 0);
        if (ct > 0) {
            for (int i = 0; i <= ct; i++) {
                list.add(sp.getString("Value[" + i + "]", ""));
            }
        }
            adp = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, list);
            Listtt.setAdapter(adp);

.

我遇到了同样的问题。我想出了一个办法来做到这一点。这可能不是最好的方法,但它做了需要做的事情。你不得不 将 SP 中删除值之后的每个值减少 1

如果你在 sp 中有像

这样的值
"value[0]","one"
"value[1]","two"
"value[2]","three"
"value[3]","four"  

删除"value[1]"后为

"value[0]","one"
"value[2]","three"
"value[3]","four"
(that's why it returns null string when you try to fetch "value[1]" because there are no such a value)

so make them a continues by inserting "value[1]". That means modify your existing value ("value[2]","three") as ("value[1]","three"). and apply this to other values also. you can simply do this by with a for loop. Then your final values would be like this.

"value[0]","one"
"value[1]","three"
"value[2]","four"

如您所见,您在回读时不会有任何空格。您必须将计数器减 1,因为现在只有 3 个值。

    void deleteItem(int element_num,int counter,SharedPreferences sp,ArrayAdapter<String> adp){


        //element_num is the element number that you want to delete
        String name_to_rmv=sp.getString("Value[" + element_num + "]", ""); //backup the value that needs to be deleted

        SharedPreferences.Editor editor=sp.edit();

        for(int i=element_num;i<counter;i++)
            editor.putString("Value[" + i + "]", sp.getString("Value[" + (i+1) + "]", "")); //read i+1 value and store it to i

        counter--;              //decrease counter
        editor.putInt("count", counter);
        editor.commit();

        adp.remove(name_to_rmv);    
        adp.notifyDataSetChanged();
    }