1

I have 3 ArrayList objects, I want to store it in the android application and I want to fetch them when application is running.

Also, I want the same order of elements as their in the ArrayList Should I go with SharedPreferences or is their any other approach to achieve it.

When I am trying it using SharedPreferences, It uses HashSet, and in that the order of the ArrayList differs at the time of fetching it.

Tell me how do I achieve this without disturbing the order?

Damian Kozlak
  • 7,065
  • 10
  • 45
  • 51
Vishal Varshney
  • 105
  • 1
  • 8
  • 5
    Possible duplicate of [Save ArrayList to SharedPreferences](http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences) – apmartin1991 Dec 30 '15 at 09:25
  • how to save it, can you tell me a sample code for doing this – Vishal Varshney Dec 30 '15 at 09:26
  • click the link in the comment above, it has all of the required code, if you cannot then figure out the code then tell me what your struggling with and I will do my best to help you. – apmartin1991 Dec 30 '15 at 09:28
  • 1
    Instead of answering the question, I would start that keeping `ArrayList` in `SharedPreferences` is bad idea and you should avoid it, using other techniques, like database etc. – Damian Kozlak Dec 30 '15 at 09:41
  • Agree with @DamianKozlak . Try database or Realm( https://realm.io ) instead. – RockerFlower Dec 30 '15 at 10:15

2 Answers2

2

You can convert the arraylist to string using below code.

ArrayList<String> arr = new ArrayList<>();
    arr.add("cat");
    arr.add("dog");
    arr.add("bird");

    // Convert the ArrayList into a String.
    String res = String.join(",", arr);

now save res in preferences

while retriving split it using "," and get the same order. Not efficient but will solve the issue.

Geo Paul
  • 1,777
  • 6
  • 25
  • 50
2

If you are already using gson in you project then you can convert that string list to json object and put it in sharedpreference as normal string and when you extract that string from preference convert it back into ArrayList. This seems very easy to me.

private List<String> searchHistoryList;
 Type listType = new TypeToken<ArrayList<String>>() { // object can be String here
            }.getType();
String previousHistory = sp.getString("KEY");
            searchHistoryList = new Gson().fromJson(previousHistory, listType);

i have successfully used this in one of my project and it seems to be working fine even if there is an Object. MAke sure to add any null check if required.

silentsudo
  • 6,730
  • 6
  • 39
  • 81