首页 文章

SharedPreferences在重新启动后不保存所有数据

提问于
浏览
1

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

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

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

我有基本的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++;
}

}

3 回答

  • 1

    问题是关于用于保存项目的标记 . 看到这条线:

    dummyname = dummyname + num;
    

    您可以按以下格式添加项目:

    task0
    task1
    task2
    

    但是你得到这种格式的 Value 观

    task0
    task01
    task012
    

    只需更改这两行代码:

    //dummyname = dummyname + num;
    //String x = sp.getString(dummyname, "not found");
    String newDummy= dummyname + num;
    String x = sp.getString(newDummy, "not found");
    
  • 0

    如果您想要保存相对较少的键值集合,则应使用Shared preference API

    Read from the shared preference:

    传递要写入的键和值,通过调用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();
    

    Write from the shared preference:

    要从共享首选项文件中检索值,请调用 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);
    
  • 0

    两件事情 :

    1)初始化SharedPreferences使用:

    sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
    

    2)你在哪里调用 addItem() 方法?

相关问题