Question

Hi guys I have recently come across a really weird problem that I cannot understand. I have tried a few work-arounds, but to no avail.

Basically as the title says, I am saving an ArrayList through the preferences but whenever I access the ArrayList it comes back shuffled.

I am drawing this to a ListView and if I have the ListView looking like:

1

2

3

4

5

6

It will come back looking like

3

2

1

6

5

4

This is my code for the onPause and on onResume

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

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    SharedPreferences prefs =           
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    SharedPreferences.Editor edit = prefs.edit();
    edit.putStringSet("TODOITEMS", new HashSet<String>(todoItems));
    edit.commit();
    super.onPause();
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    ArrayList<String> returnedItems = new ArrayList<String>  
 (PreferenceManager.getDefaultSharedPreferences
 (getBaseContext()).getStringSet("TODOITEMS",     
  new HashSet<String>()));
    todoItems.clear();
    for(int i =0; i < returnedItems.size(); i++){
        todoItems.add(returnedItems.get(i));
    }
    aa.notifyDataSetChanged();

  super.onResume();
 }
Was it helpful?

Solution 4

As the previous two answers mention, a HashSet doesn't guarantee preserving order.

One possible solution is to serialize the ArrayList into a String first, save it using putString(), and then load it using getString() and deserialize it.

Check out the second half of this answer to see how to do that: Save ArrayList to SharedPreferences

OTHER TIPS

it's because you are using a HashSet to store the values. HashSet doesn't guarantee that the order will be maintained.

you should use a TreeSet instead

check out Hashset vs Treeset

You're not actually saving the todoItems ArrayList and loading it. You're converting the todoItems ArrayList into a HashSet, saving it, then loading it again and re-constructing an ArrayList with it.

In that conversion from ArrayList to HashSet, the orders are not maintained. Checkout this answer on the differences between both: What is the difference between Set and List?

I think that is because you are saving the array to a HashSet.

According to the documentation:

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

If you want to save a sorted list, I suggest you use SQLiteDatabase. OR You can sort the list as you retrieve it from the Shared Preferences. This is not good if the list is very large however.

Collections.sort(returnedItems);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top