首页 文章

sharedpreferences:保存到ListView

提问于
浏览
0

我没有问题在sharedpreferences中保存列表并在列表视图中显示它,但我的问题是当我重新启动应用程序并尝试将项目添加到listview旧存储的项目已删除 . 有我的代码:

public void SaveDatesToList(){
    list.add(i+"");
    array = new String[list.size()];
    list.toArray(array);
    tinyDB.putListString("DATES",list);

}

public void getDates(){

for (String str:tinyDB.getListString("DATES")) {
        list.add(str);
    }

2 回答

  • 0

    Please Try this two function store arrlist and retrive arraylist in sharedprefrence

    private void storeArray() {
        ArrayList<String> arr1 = new ArrayList<>();
        SharedPreferences prefs = this.getSharedPreferences("Demo", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = prefs.edit();
    
        arr1.add("A");
        arr1.add("B");
        arr1.add("C");
        arr1.add("D");
        arr1.add("E");
    
        Set<String> set = new HashSet<String>();
        set.addAll(arr1);
        edit.putStringSet("yourKey", set);
        edit.commit();
    }
    
    private void retriveArray() {
        SharedPreferences prefs = this.getSharedPreferences("Demo", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = prefs.edit();
        Set<String> set = prefs.getStringSet("yourKey", null);
        ArrayList<String> sample = new ArrayList<String>(prefs.getStringSet("yourKey", null));
        Log.d("Check Size", "Check Size" + sample.size());
    
        if (sample.size() > 0) {
            for (int i = (sample.size() - 1); i >= 0; i--) {
                Log.d("Array Value", "Array Value" + sample.get(i));
            }
        }
    }
    
  • 1

    问题是您不断覆盖旧数据,因为您可能无法检索旧数据并将新数据附加到旧数据 .
    SharedPreference 中检索旧数据,并将它们与新的ArrayList结合使用 . 然后存储组合的ArrayList .

    组合示例 ArrayList<String>

    ArrayList<String> first = new ArrayList<String>();
    ArrayList<String> second = new ArrayList<String>();      
    //Let both arraylists have some data
    first.add("data1");   
    second.add("data2");   
    
    // now first contains "data1" and "data2"
    first.addAll(second);
    

    现在ArrayList first 拥有所有数据 . 例如,做

    editor.putStringSet("KEY", first).apply();
    

相关问题