【问题标题】:Create a List of saves from one button一键创建保存列表
【发布时间】:2015-08-08 21:59:19
【问题描述】:

我的项目需要帮助。我需要能够按下使用共享首选项的保存按钮,并且每次按下该按钮时,我都需要它来获取保存的数据并将其像列表一样堆叠在彼此下方。关键值是“结果”。因此,保存按钮获取字符串和整数并将其放置到我的主要活动 XML 布局中。但是,如果我用不同的整数或字符串再次按保存,它将替换我最初保存的原始字符串和整数。如果我第一次保存它,我希望它能够保留原始字符串和整数,如果我第二次保存,则在原始字符串和整数下面创建一个新字符串和整数,以此类推。请帮忙!

这是我的储蓄活动:

    public void save(View view){

    Date date = new Date();
    String stringDate = DateFormat.getDateInstance().format(date);

    SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor =sharedPreferences.edit();
    editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());

    editor.commit();
    Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();

}  

这是我的加载活动:

    resultPhysical = (TextView) findViewById(R.id.home);

    SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
    String physicalresult = sharedPreferences.getString("result", DEFAULT);
    String physicalresult2= sharedPreferences.getString("result2", DEFAULT);
    if (physicalresult.equals(DEFAULT)){
        Toast.makeText(this,"No Data Found", Toast.LENGTH_LONG).show();
    }
    else{
        resultPhysical.setText(physicalresult);
    }


}

【问题讨论】:

    标签: java android xml string button


    【解决方案1】:

    您可以轻松地保存它们,只需创建一个引用保存结果大小的额外变量,以便您可以循环它们。要开始保存,请获取大小,然后使用索引保存

    int size = sharedPreferences.getInt("size", 0); // if it doesn't exist, get 0
    // then save the result like
    editor.putString("result" + String.valueOf(size), String.format(stringDate, date) + " - " + text_view5.getText().toString()); // just add index to result
    // then increase the size
    editor.putInt("size", ++size);
    editor.commit();
    

    加载结果

    StringBuilder results = new StringBuilder();
    int size = int size = sharedPreferences.getInt("size", 0); // get the size to start looping
    if(size == 0){ // if results are empty
        // show toast there is no saved result
    } else { //start looping
        for(int i = 0; i < size; i++){
            String temp = sharedPreferences.getString("result" + String.valueOf(i), DEFAULT);
            results.append(temp + " ");
        }
        resultPhysical.setText(results.toString());
    }
    

    【讨论】:

    • 嗯..它似乎应该工作。即使在 logcat 中也没有错误,但由于某种原因,即使在我保存后它也不会更改默认文本
    • @JoshSmith 对不起,我不明白你的意思
    • 当没有数据时,我使用 TextView id:home 说“未找到数据”。所以我需要让数组列表显示在那个 TextView 上……我想
    • @JoshSmith 不,您不需要将整个数组设置为 TextView,我只是为了展示如何根据需要检索整个结果。要获取最后保存的使用String lastResult = sharedPreferences.getString("result" + String.valueOf(size-1), DEFAULT);
    • 我怎样才能让它在文本视图内的一个数组列表中显示每个保存?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2013-07-13
    相关资源
    最近更新 更多