Amix Amix - 3 months ago 75
Android Question

how to use shared preferences to save array list items?

I use these 2 methods for save and load my array list and I need to save my array list after each item dynamically added to array.

public void addItems(int howMany){
if (howMany > 0) {
int lastInsertedIndex = 11;
for (int i = lastInsertedIndex + 1; i <= lastInsertedIndex + howMany; i++) {
mList.add("Item " + i);
notifyItemInserted(mList.size() - 1);
}
lastInsertedIndex = lastInsertedIndex + howMany;
}
}


and my save and load method:

public boolean saveArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Set<String> set = new HashSet<String>();
set.addAll(mainListAdapter.mList);
editor.putStringSet("list", set);
return editor.commit();
}

public ArrayList<String> getArray() {
SharedPreferences sp = context.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
//NOTE: if shared preference is null, the method return empty Hashset and not null
Set<String> set = sp.getStringSet("list", new HashSet<String>());
return new ArrayList<String>(set);
}


My problem is : when I add a new item with button nothing happen and like the array list is full how to fix this ?

Answer

The the following:

Declare myList globally:

ArrayList<String> myList = new ArrayList<String>();

For setting value:

for (int i = 0; i < totalSize; i++) {
    PreferenceManager.getDefaultSharedPreferences(this)
                     .edit()
                     .putString("number" + i, value + "").commit();         
}

For getting value:

for (int i = 0; i < totalSize; i++) {
   myList.add(PreferenceManager.getDefaultSharedPreferences(this)
                               .getString("number" + i, "0"));
}

NOTE:- totalSize is the size of your array

enjoy coding.............

Comments