I have an ArrayList
with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences
but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences
isn't the way to go about this? Is there a simpler method?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
Also with Kotlin:
Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple.
to put
to get
Android SharedPreferances allow you to save primitive types (Boolean, Float, Int, Long, String and StringSet which available since API11) in memory as an xml file.
The key idea of any solution would be to convert the data to one of those primitive types.
I personally love to convert the my list to json format and then save it as a String in a SharedPreferences value.
In order to use my solution you'll have to add Google Gson lib.
In gradle just add the following dependency (please use google's latest version):
Save data (where HttpParam is your object):
Retrieve Data (where HttpParam is your object):
Why don't you stick your arraylist on an Application class? It only get's destroyed when the app is really killed, so, it will stick around for as long as the app is available.
Use this custom class:
How to use:
I used the same manner of saving and retrieving a String but here with arrayList I've used HashSet as a mediator
To save arrayList to SharedPreferences we use HashSet:
1- we create SharedPreferences variable (in place where the change happens to the array)
2 - we convert the arrayList to HashSet
3 - then we put the stringSet and apply
4 - you getStringSet within HashSet and recreate ArrayList to set the HashSet.
public class MainActivity extends AppCompatActivity { ArrayList arrayList = new ArrayList<>();