0) { for (int i = 0; i (this, -6ren">
gpt4 book ai didi

android - 删除android中的共享首选项

转载 作者:行者123 更新时间:2023-11-30 02:09:46 25 4
gpt4 key购买 nike

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

    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();

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

我如何填充适配器

 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);

. Example output

最佳答案

我遇到了同样的问题。我想出了一个办法来做到这一点。这可能不是最好的方法,但它做了需要做的事情。你不得不将 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();
}

关于android - 删除android中的共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30268597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com