Reputation: 61
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?
Upvotes: 1
Views: 3007
Reputation: 720
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!
Upvotes: 1
Reputation: 1313
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!
Upvotes: 0
Reputation: 843
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
Upvotes: 0