Amix Amix - 1 year ago 177
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>();
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 Source

The the following:

Declare myList globally:

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

For setting value:

for (int i = 0; i < totalSize; i++) {
                     .putString("number" + i, value + "").commit();         

For getting value:

for (int i = 0; i < totalSize; i++) {
                               .getString("number" + i, "0"));

NOTE:- totalSize is the size of your array

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download