sharedpreferences : Save to ListView

1.2k Views Asked by At

I have no problem to save list in sharedpreferences and show it in list view but my problem is when i restart the app and try to add items to listview old stored items removed . there is my code:

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

There are 2 best solutions below

2
On

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));
        }
    }
}
6
On

The problem is that you keep overwriting the old data because you probably do not retrieve the old data and append the new data to it.
Retrieve your old data from the SharedPreference and combine them with your new ArrayList. Then store the combined ArrayList.

Example of combining 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);

Now the ArrayList first has all the data. And for example do

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