4

What to do if the TYPE of preference changed in Android Preferences? For instance if Boolean changed into ListPreference?

Really noone at Google thought about Preference Migrations?

The only sensible way for now seems to version preferences and mark for removal preferences that changed with a given version..?

CeDeROM
  • 506
  • 5
  • 10

2 Answers2

3

Try to read key with new data type, in case of ClassCastException exception delete "old" key, and create new key with same name but new type. Something like this:

SharedPreferences prefs;
String key = "key"; 

prefs = PreferenceManager.getDefaultSharedPreferences(this);

if (prefs.contains(key)) {
    // key exists, so tetermine it's type
    try { 
        prefs.edit().get<old_type_name>(key, <default_old_type_value>);
    } catch (Exceprtion e) {
        if (e instanceOf ClassCastException) {
            prefs.edit().remove(key).apply();
        }
    }
} 

// we are here if no key exists or key removed
prefs.edit().put<new_type_name>(key, <new_type_value>).apply(); 

and if needed do check if (prefs.contains(key)) ... only once on first app start.

Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
  • Thanks :-) I have already noticed importance of ClassCastException as possible settings changes / integrity problems. Also deleting old keys and re-creating them with default values was my choice :-) – CeDeROM Oct 30 '16 at 21:18
0

I did something that works on raw SharedPreferences and does not need a PreferenceFragment:

  • introduced settings version.
  • preferences are stored in xml resources both with dedicated xml strings.
  • split code to load, migrate, set default settings on application start.
  • created two string arrays versions and keys - that keep track of preference changes - keys is a comma separated string - with the same index this pair keeps information on given version migration.
  • check the current version from stored settings and verify against versions stored in string arrays, if its current version is older (lower number) then delete keys provided in a keys string array with the same index (needs string split) and re-create them with default values.

This gives me a nice way of settings migration, based purely on strings xml resources and no code changes, also it should migrate step by step all following versions if user did not update the application frequently :-)

It is also good to mark recent migration for a user review of recent changes..

CeDeROM
  • 506
  • 5
  • 10