Save ArrayList in shared preferences

房东的猫 提交于 2019-12-01 06:08:38
Salman Khakwani

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<Boolean> 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<Boolean> 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<Boolean> 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.

public static boolean saveArrayList()
{

SharedPreferences sp = SharedPreferences.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
mEdit1.putInt("Status_size", sKey.size()); /* sKey is an array List*/ 

    for(int i=0;i<sKey.size();i++)  
    {
    mEdit1.remove("Status_" + i);
    mEdit1.putString("Status_" + i, sKey.get(i));  
    }

    return mEdit1.commit();     
}

**Loading Array Data from Shared Preferences**

 public static void loadArrayList(Context mContext)
 {  
    Shared Preferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext);
    sKey.clear(); //skey is arraylist
    int size = mSharedPreference1.getInt("Status_size", 0);  

    for(int i=0;i<size;i++) 
    {
      sKey.add(mSharedPreference1.getString("Status_" + i, null)); //skey is arraylist
    }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!