Resetting the preferences on first launch of an app

If you want to reset or change preferences of an app at the first start here is an example of code you can put in an event as onCreate of the main activity:

        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
        }

This code saves a version number of preferences if the version is less than a predetermined value (newPrefsVersion).
In this example, the preferences are deleted but you can edit or delete individual entries of the preferences with the methods provided by the class Editor.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.