0

I'm using a TreeMap because it's the most efficient data structure for storing the information I need. I have to be able to persist the TreeMap for future use, so is there a way for me to store it in a SharedPreferences object, maybe serialize it before doing so?

I'm aware of this method here, but using ObjectSerializer from the Apache Pig project makes Eclipse crash. When I run the app, the status bar at the bottom never goes past the message "Launching [app name] 100%", until it throws the following error message:

Unable to execute dex: Java heap space
Unhandled event loop execution

Is there anything I can do to store the TreeMap inside the shared prefs?

Community
  • 1
  • 1
Matthew Quiros
  • 13,385
  • 12
  • 87
  • 132

1 Answers1

3

If you want to serialize/deserialize, you can go for serializing TreeMap into JSON format as a string object and then store it whereever you want to store it. Later you would be able to deserialize it from JSON format.

You can use famous jackson library for it as jackson library is the industry standard and is free. See at http://wiki.fasterxml.com/JacksonHome.

Edit: JSON format also ensures that you can read the persisted data in other programs as it would be very much readable. Not sure if Jackson JSON library works on android. If so find out some other library for JSON in android.

Niraj Nawanit
  • 2,431
  • 3
  • 16
  • 11
  • Not sure if I understand you correctly--you mean, instead of using a TreeMap, store my data in JSON format and store/retrieve it from the shared prefs as a String (that way, there's no more need to serialize/deserialize)? Because I might lose the sort order of my data, which is why I used a TreeMap in the first place. – Matthew Quiros Sep 01 '12 at 06:20
  • No.. you use TreeMap only. But while storing into SharedPrefrences, you convert it into JSON format. When you read it from Shared Preferences, you read it from there and convert it back to TreeMap. – Niraj Nawanit Sep 01 '12 at 06:22
  • the logic of code would be something like this. To serialize: prefs.edit().putString(key, toJSONString(treemap)). To deserialize: TreeMap treemap = new TreeMap((Map)fromJson(prefs.edit().getString(key))) – Niraj Nawanit Sep 01 '12 at 06:27
  • Good solution, but I'll probably just serialize the object myself and not put it in a shared prefs. I'll have to take time studying Jackson, importing it increases my app's file size, and I think converting it from TreeMap to JSON is an overhead. I might as well directly serialize it. Anyway, thanks! – Matthew Quiros Sep 01 '12 at 07:22