Storing user’s profile – the easiest way

It’s quite obvious that if the only thing you need to store in your app are user profile, app’s settings and other equally simple values, there’s no need to spend extra time creating a whole new relational database just for this purpose.

Still, even with SharedPreferences, I’ve seen some developers going the long way and putting/getting all the key-value pairs manually in and from SharedPreferences, while there’s a much easier way – use Gson (or any other serialization library like Square’s Moshi) for a single read/write operation.

Let’s take a look at a simple UserProfile class:

public class UserProfile {
    private String mFirstName, mLastName;
    private String mEmail;
    private List<Item> mItems;
    //... dozens of other fields
}

Now, let’s create a basic Gson instance:

Gson gson = new GsonBuilder().create();

We’re now ready to store the whole object by serializing it to a single String:

mSharedPreferences.edit().putString(KEY_USER_PROFILE, gson.toJson(userProfile)).apply();

and deserialize that String later to get our proper Java object back:

UserProfile userProfile = gson.
fromJson(mSharedPreferences.getString(KEY_USER_PROFILE, null), UserProfile.class);

That’s it. No boilerplate, no ORMs. Mix it with singleton pattern, and you’re ready to go.

Leave a Reply

Your email address will not be published. Required fields are marked *