0

I have a HashMap<Integer, ArrayList<MyTeam>> where the class MyTeam is a POJO. There will be at most 5 items in each ArrayList object. Is it possible to save this kind of HashMap to SharedPreferences? If not, what is another alternative? I need this data to be saved when the app is closed and reloaded when it starts up.

I've looked at this answer but the Key and Value attributes are both String and my case is a bit more complicated than just String data types. Will this method still work? Is there a better way?

Community
  • 1
  • 1
David Velasquez
  • 2,346
  • 1
  • 26
  • 46

1 Answers1

0

Is it possible to save this kind of HashMap to SharedPreferences?

Not directly. You are welcome to convert that into JSON and save it as a string preference. Then, to load it back in, you would read in the string and use a JSON parser to reconstitute your objects.

This class demonstrates the basic technique, though it is saving a List<Uri>, not a HashMap<Integer, ArrayList<MyTeam>>. I specifically used this sample to demonstrate the use of the built-in JSONReader and JSONWriter classes; for a real app, I would consider Gson or a similar JSON parsing library.

If not, what is another alternative?

Save it to a SQLite database, probably through a couple of tables. Or, save it to some sort of file, in a file format of your choosing (e.g., JSON, XML).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491