So, you have a nifty neat application that is storing data based on user input. You allow the user to choose a resource (an icon, maybe a sound file) to be stored with that data record. Everything is going great until you add new resources to your project. Suddenly the icons are mixed up, no longer the icon originally chosen. Welcome to the world of machine-generated code.
The solution is rather simple, just not presented anywhere in the Android docs. We’ll create an Enum that associates the Resource IDs with our own local IDs. This way, we can store the local IDs, so that the SDK can change the resource IDs as much as it wants. Full code for the enum is at the bottom.
From now on, we retrieve resources with the Enum:
mIcon.setImageDrawable(getResources().getDrawable(ReminderResources.AUDIO_ICON.resourceId()));
Storing the ID in SQLite is also very simple, storing our ID instead of the generated one.
initialValues.put(KEY_ICON, r.getIconID().localId());
Then, when we retrieve the ID from SQLite, we use the ‘get()’ method to retrieve the Enum:
reminder.setIconID(ReminderResources.get(cursor.getInt(iconColumn)));
Full code for the Enum:
public enum ReminderResources {
AUDIO_ICON (0, R.drawable.audioicon),
FORM_ICON (1, R.drawable.form),
FINGER_ICON (2, R.drawable.finger),
LAUNDRY_ICON (3, R.drawable.laundry),
TASK_ICON (4, R.drawable.task),
BELL (5, R.drawable.bell);
private final int localId; // in kilograms
private final int resourceId; // in meters
ReminderResources(int localId, int resourceId) {
this.localId = localId;
this.resourceId = resourceId;
}
public int localId() { return localId; }
public int resourceId(){ return resourceId;}
private static final Map<Integer,ReminderResources> lookup
= new HashMap<Integer,ReminderResources>();
static {
for(ReminderResources s : EnumSet.allOf(ReminderResources.class))
lookup.put(s.localId, s);
}
public static ReminderResources get(int code) {
return lookup.get(code);
}
}