0

I am assigning an arraylist to another, also storing it in SharedPreferences. Problem is that while fetching the arraylist from SharedPreferences. the order of arraylist is different i.e. values stored on indexes are different in the fetched arraylist .

I am using the following code for storing: Here, I am qarrayoff arraylist to list1. while printing elements of list1 it is in different order as in qarrayoff

ArrayList<String> list1 = new ArrayList<String>();
list1.addAll(qarrayoff);// fetch the data

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("SAVEDATA", new HashSet<String>(list1));
edit.commit();  

I want the same order i.e. same sequence of elements in both arraylist. How to achieve it?

Zanon
  • 29,231
  • 20
  • 113
  • 126
Vishal Varshney
  • 105
  • 1
  • 8

2 Answers2

1

The simplest way to solve your problem would be to use this, TinyDB. It simplifies the use of SharedPreferences in your app.

Then you can simply do something like this,

TinyDB tinydb = new TinyDB(context);
tinydb.putListString("ListArray", mListArray);

then you can get the data using this,

tinydb.getList("ListArray");

The order will always be maintained.

UPDATE

To clear your confusion, there is nothing like TinyDB in Android. It is just a wrapper class around SharedPreferences to make your life a bit easier.

Your data will always be stored in SharedPreferences, TinyDB class is just an utility class. So the data will remain stored in the SharedPreferences even after you close your app or restart it.

Aritra Roy
  • 15,355
  • 10
  • 73
  • 107
1

you could convert the content of ArrayList as JSONArray as save it in the SharedPreference as String. E.g.

 JSONArray jArray = new JSONArray(list1);
 edit.putString("SAVEDATA",jArray.toString());

but you will have to pay the extra effort, to parse your JSONArray when you retrieve it. Alternatively you could store each single entry, using its index as key, and the size of the ArrayList . This way, to reconstruct the ArrayList, you will have to loop size times, and use the index of the loop as key to retrieve the entry

Blackbelt
  • 156,034
  • 29
  • 297
  • 305