13

I would like to know what would be the best option to store a custom Java object that I have in my application. I've read about serialization but it seems to be quite slow.

What is the best option?

Macarse
  • 91,829
  • 44
  • 175
  • 230
feeder1803
  • 141
  • 1
  • 1
  • 3
  • Have you tried [Parcel](http://developer.android.com/reference/android/os/Parcel.html). – Mudassir Mar 16 '11 at 12:35
  • possible duplicate of [Best method for saving data - preferences, sqlite, serializable or other?](http://stackoverflow.com/questions/4962426/best-method-for-saving-data-preferences-sqlite-serializable-or-other) – Macarse Mar 16 '11 at 12:35
  • "custom Java object" could be anything in terms of data complexity and size. Please elaborate. – olivierg May 12 '11 at 19:25

2 Answers2

16

If you're not storing an over abundance of data you can use Gson to convert a Java object to a Json string and store the string in your app preferences. Gson has a toJson(obj) method and visa-vis.

Getting data out of app preferences and into an object:

String json = appSharedPrefs.getString("someName","");    
return gson.fromJson(json, YourModel.class);

To get data from your object into app preferences:

String json = gson.toJson(obj);

Then prefsEditor.putString("someName", json).apply().

Bill Mote
  • 12,644
  • 7
  • 58
  • 82
  • 1
    Could you please post a reference link or code sample? Thanks. – Kingsolmn May 12 '11 at 17:59
  • Not a problem. That has been very handy ;) – Bill Mote May 13 '11 at 11:52
  • 1
    Ok, maybe I need to sleep more often but I am having an issue using this in my Android project. Do I need to manually include the JAR for Gson (if so, where can I find it?) or am I missing something for the import (using Eclipse, cannot resolve the package com.google) - thanks. @Bill – Kingsolmn May 20 '11 at 06:16
  • Yes. GSON is an external library you have to add. Google it. Don't recall the exact URL. – Bill Mote May 20 '11 at 10:04
  • Thanks again, @Bill. I just needed a slap on the back of the head and some sleep! The URL is: http://code.google.com/p/google-gson/downloads/list – Kingsolmn May 20 '11 at 16:46
  • It's too late, but maybe can read this: You should use Maven or Gradle, they're very good options instead of download jar files, then adding to your project. Maven and Gradle do this automatically – Antonio May 14 '15 at 16:29
  • At the time of this answer @Antonio maven for Android was HORRIBLE and Gradle wasn't an option. Today, however, as you point out, there are many better ways to handle adding a JAR or AAR to your project ;) – Bill Mote May 14 '15 at 18:14
  • 1
    @feeder1803 mark this one as verified. It's working. This answer desires the verified answer. – Prasad Jan 06 '17 at 07:40
5

You should read:

  1. Best method for saving data - preferences, sqlite, serializable or other?
  2. Data Storage
Community
  • 1
  • 1
Macarse
  • 91,829
  • 44
  • 175
  • 230