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 */ |
02 | public static final String KEY_PREFIX = |
03 | "com.our.package.KEY" ; |
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 |
10 | private String getFieldKey( int id, String fieldKey) { |
11 | return KEY_PREFIX + id + "_" + fieldKey; |
Notice how getFieldKey() gives us a unique identifier per field name and per user.
No comments:
Post a Comment