1

I'm building an app that has a favourites list, but when I exit the app, the favourites list is reset to nothing because the list is not being saved (since lists can't be saved in SharedPrefs). How can I save an ArrayList OR String[] in Android? If you recommend Serialization or a Local Database, could you please explain what these are and mean? I've heard the terms and followed tutorials but do not understand.

Maybe another approach to the same question is how would you normally build a favourites list?

420blazeit
  • 61
  • 1
  • 8

3 Answers3

1

There's a question that explains it in a very nice way:

Save ArrayList to SharedPreferences

From its answer (I've already tested it), after API 11 you can do something like this:

//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

I summarized his answer, but you should check the complete answer. It's really helpful!

Community
  • 1
  • 1
cristianorbs
  • 670
  • 3
  • 9
  • 16
  • It is not the same because I am not asking to save it in SharedPreferences because that is not what SharedPreferences should be used for, especially if it is a large array. Thanks! I'll try this, but like I said, hopefully I can find an alternative to SharedPreferences, as mentioned in my post, I want to find the 'default''/recommended way to save favourites lists. – 420blazeit Apr 27 '16 at 20:10
  • Sure. I didn't figured out that it was a large array. Since you asked for simple I thought it would be helpful. Anyway, we always should keep in mind that simple is not always best. I'll edit it since it's not duplicated. My mistake – cristianorbs Apr 27 '16 at 20:23
0

Option1: easiest. Iterate over arraylist and save each element into sharedPreferences

option2: convert arraylist into a string. Then save into shared pref.

option3: save your data into a database. Google how to use sqllite with android

Rusheel Jain
  • 843
  • 6
  • 20
  • I'd like to try option 3 but my issue is that I cannot find a saving specific tutorial for databases like SQLite, preferably I don't want to have to learn SQLite for days just to save a favourites list. – 420blazeit Apr 27 '16 at 20:13
  • To save stuff in database, a very simple way is using Sugar ORM, as suggested by Isaac Urbina in the other answer. – cristianorbs Apr 27 '16 at 20:29
0

You can use Sugar ORM library for Android. It will create for you the database you need by simply making the object class of your ArrayList to extend SugarRecord. For example, if your List type is ArrayList you have to make your Books class extend SugarRecord, and then in your Activity iterate in a loop through the items and set item.save() and it is saved to the database. I have a sample project here. If you have any question send me a PM. Hope it helps!

Isaac Urbina
  • 1,295
  • 11
  • 21