0

I am an iOS developer who is trying to learn Android and I would like to make sure that I am following best practices.

I have custom objects that need to be accessible by 1 -> m activities and they need to be saved when the application closes. Currently I am using SharedPreferences, code below, to save them but I am not sure if it is the best route. Should I be using a singleton? Is there a better way?

SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userProfile);
prefsEditor.putString("UserProfile", json);
prefsEditor.commit();

gson = new Gson();
json = mPrefs.getString("UserProfile", "");
UserProfileObject outObject = gson.fromJson(json, UserProfileObject.class);
Juan Cruz Soler
  • 8,172
  • 5
  • 41
  • 44
user1079052
  • 3,803
  • 4
  • 30
  • 55

3 Answers3

2

A singleton won't be saved when the application exits. Really your options are:

*SharedPreferences. Good for a small number of key/value pairs

*Database. Good for relational data

*File on disk, in whatever format you prefer. Good for any amount of data, but you may need to write a custom parser.

Storing json in a shared preference is a bit weird. Its not horrible so long as you aren't storing a lot of keys in there, but it makes it seem like you didn't know how to write a file.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

@Gabe has provided a good answer. I am adding my 2 cents to it

I personally do not like to save serialised data in SharedPreferences. Instead I would use local db storage such as SQLite or Realm to store it. The reason being serialisation/deserialisation involves marshalling/unmarshalling objects using reflection which could potentially hit performance in a negative way.

In short, Use local db for storing complex / relational data and SharedPreferences for storing simple data

Much Overflow
  • 3,142
  • 1
  • 23
  • 40
0

I think if your UserProfileObject can be easily constructed from Json and it doesn't contain any sensitive data (i.e. password), might be fine just having it in SharedPreferences (just save the json string like what you are doing).

Using a singleton SessionManager / ProfileManager class with that should be sufficient enough. Even though it might be used by 1 -> m activities, it only hits the SharedPreferences once using the singleton. Just make sure you keep the copy of the data in the singleton and in SharedPreferences in sync when there are changes. Or just dump the singleton all together and hit the SharedPreferences every time you need it (less worries about keeping copies in sync), don't think your use case will hammer it that much.

Bundeeteddee
  • 724
  • 11
  • 19