Nel caso si vogliano azzerare o modificare le preferenze di un’app al primo avvio ecco un esempio di codice da utilizzare in un evento come onCreate dell’activity principale:
1 2 3 4 5 6 7 8 9 10 11 |
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); String key = "prefs_version"; // the key for the version number int currPrefsVersion = sharedPreferences.getInt(key, 1); int newPrefsVersion = 2; // insert here the new version of the preferences if (currPrefsVersion < newPrefsVersion) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); // reset the preferences editor.putInt(key, newPrefsVersion); // put the new version number of the preferences editor.commit(); // save the preferences } |
Questo codice salva un numero di versione delle preferenze se la versione è inferiore a un prefissato valore (newPrefsVersion).
In questo esempio le preferenze sono cancellate ma è possibile cancellare o modificare solo alcune voci delle preferenze con I metodi messi a disposizione dalla classe Editor.