Save ArrayList in shared preferences

前端 未结 2 813
生来不讨喜
生来不讨喜 2021-01-13 07:16

i am searching for hours to find out why saving boolean list in shared preferences is not working.

The methods are not saving or loading something... the loadmethod

2条回答
  •  臣服心动
    2021-01-13 08:03

    Just make the following changes in your code, and it should work. Take SharedPrefrences mSharedPrefs as your class variable.

    public class SaveLoadTraining 
    {
    private Context context;
    public static final String PREFS_NAME = "ListFile";
    private ArrayList list;   
    private SharedPreferences mSharedPrefs;
    
    public SaveLoadTraining(){
        this.context = getApplicationContext();
        mSharedPrefs = context.getSharedPreferences(PREFS_NAME, 0);
    }
    

    Make 2 different Methods for removing and adding values to Shared Preferences and do it in two commits instead of 1 Commit.

    1st Method for Removing the List

    public void removeArray(ArrayList list)
    {
    SharedPreferences.Editor editor = mSharedPrefs.edit();
    
    int size = list.size();
    
        for (int i = 0; i < size; i++) {
            editor.remove("list_"+i);
        }
        editor.commit();
     }
    

    2nd Method for Adding the List

    public void addArray(ArrayList list)
    {
    SharedPreferences.Editor editor = mSharedPrefs.edit();
    
        int size = list.size();
        editor.putInt("list_size", size);
    
        for (int i = 0; i < size; i++) {
            editor.putBoolean("list_"+i, list.get(i));
        }       
        editor.commit();
     }
    

    I hope this will work.

提交回复
热议问题