Sunday, December 22, 2013

Method 1: Flattened Objects with Field Keys

Method 1: Flattened Objects with Field Keys

The idea here is that, although SharedPreferences only stores primitive types, an object construct is ultimately a “bag” of primitives. So we can decompose an object into a set of primitives and store each one of those individually with a unique key. However we do need to keep track of which saved field belongs to which object if we want to reconstruct our objects from storage.
So before writing the CRUD methods on a given User object in our UserPrefs class, we need to define unique keys on each User class member. For convenience we can write a method to ensure key uniqueness across the board:
01/** The prefix for flattened user keys */
02public static final String KEY_PREFIX =
03            "com.our.package.KEY";
04 
05/** Method to return a unique key for any field belonging to a given object
06* @param id of the object
07* @param fieldKey of a particular field belonging to that object
08* @return key String uniquely identifying the object's field
09*/
10private String getFieldKey(int id, String fieldKey) {
11       return  KEY_PREFIX + id + "_" + fieldKey;
12}
Notice how getFieldKey() gives us a unique identifier per field name and per user.

1 comment:

  1. Hey dude…good article. You are the best writer that I have come across so far. You have a knack for words, I must say. I have bookmarked your web page. Please keep writing such wonderful blogs. For freelancers, who are working to earn the extra bucks…your article is worth millions of dollars. You are my FPG (friend, philosopher and guide)! I have wholeheartedly stepped into the freelance zone and checked out some sites like Professional Logo Design, Sell Mobile Application. You have woken me up to the possibilities of marketplaces. Thank you and keep posting!

    ReplyDelete