Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Shared Preferences Type Migration

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..?

like image 503
CeDeROM Avatar asked Sep 17 '25 22:09

CeDeROM


1 Answers

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.

like image 67
Andrii Omelchenko Avatar answered Sep 19 '25 12:09

Andrii Omelchenko