android - SharedPreferences 重启后不保存所有数据

标签 android listview sharedpreferences

我是 Android 应用程序开发的新手,我应该为一门类(class)制作一个 TodoList 应用程序。但是我代码中的 SharedPreference 不起作用。我不知道我是否应该在特定方法(如 onCreate 或 onStop)中以特定方式使用它。

它永久保存用户输入的第一个输入,但在同一位置: enter image description here (“task0” 是我用来跟踪在 addStuff 方法中用作 “putString” 参数的不同变量名称,以避免替换值)

它在同一个 session 中保存之后的输入,但是如果用户结束该 session ,“t”之后的所有那些值都将消失。如果用户重新启动应用程序并输入其他内容(如“g”),它会将“g”保存在相同的第 3 个位置。

我有基本的 Java 知识,我试图理解使用它会发生什么,但失败了。请让我知道错误在哪里以及如何正确使用 SharedPreferences。

public class TodoActivity extends AppCompatActivity {

public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";

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

    list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
    taskBox = (EditText) findViewById(R.id.box);
    s = taskBox.getText().toString();

    items = new ArrayList<String>();

    itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
    list.setAdapter(itemsAdapter);

    //add items to list
    items.add("First Item");
    items.add("Second Item");

    //restore
    SharedPreferences sp = this.getSharedPreferences("itemsList", 0);

    //checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
    String dummyname = "task";
    text.setText(String.valueOf(counter));//since counter is again at
    for(int c=0; c<=50; c++){
        String num = String.valueOf(c);
        dummyname = dummyname + num;
        String x = sp.getString(dummyname, "not found");
        if (x.equalsIgnoreCase("not found")){
            counter=c-1;
            break;
        } else {
            items.add(x);
            text.setText(dummyname);
        }
    }

}

public void addItem(View v){
    s = taskBox.getText().toString();
    itemsAdapter.add(s);//adding the new task as string

    String temp = String.valueOf(counter);
    newtask = "task" + temp;

    //trying to store the new tasks with different variable names to avoid being replaced
    text.setText(newtask);
    SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
    SharedPreferences.Editor e = sp.edit();
    e.putString(newtask,s);
    e.apply();

    counter++;
}

最佳答案

如果您要保存的键值集合相对较小, 你应该使用 Shared preference接口(interface)

从共享首选项中读取:

传递您要写入的键和值,通过在您的 SharedPreferences 上调用 edit() 创建一个 SharedPreferences.Editor。

使用此方法传递要保存的键和值 putInt() ,putString() ,然后调用 commit() 到保存更改。例如:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();

从共享首选项写入:

要从共享首选项文件中检索值,请调用 getInt()getString() 等方法, 为您想要的值提供键,如果键不存在,则可选择返回默认值。例如:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);

关于android - SharedPreferences 重启后不保存所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40188170/

相关文章:

java - 有目的地将变量传递给两个 Activity

java - 点击 Android 滑动 fragment

Android convertView,用还是不用?

C extern clock_t 变量在文件中未按预期工作;

dart - 在 Dart/Flutter 中从集合转换为列表?

android - 在一天中的特定时间重置整数值

android - 是否可以对多种语言使用相同的字符串资源文件?

android - 如何在未显示上下文菜单时停止将长按作为短按处理

javascript - jQuery Mobile 未刷新 Backbone.js 支持的列表( ListView (‘refresh’))

java - 保存按钮状态(启用和禁用)