How to clear old preferences when updating Android app?

后端 未结 4 1515
庸人自扰
庸人自扰 2020-12-30 05:32

I have an app on the Google Play market. For various reasons that I won\'t bother going into, I have changed the type of some of my preferences. For example a preference t

4条回答
  •  我在风中等你
    2020-12-30 05:57

    The SharedPreferences.Editor class has a clear() function, what removes all your stored preferences (after a commit()). You could create a boolean flag which will indicate if updated needed:

    void updatePreferences() {
        SharedPreferences prefs = ...;
        if(prefs.getBoolean("update_required", true)) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.clear();
    
            /*....make the updates....*/
    
            editor.putBoolean("update_required", false)
            editor.commit();
        }
    }
    

    And after that you need to call this in your main (first starting) activity, before you access any preferences.

    EDIT:

    To get the current version (The versionCode declared in the manifest):

    int version = 1;
    try {
        version = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    
    if(version > ...) {
        //do something
    }
    

    EDIT

    If you want to do some updating operation, whenever the version changes, then you can do something like this:

    void runUpdatesIfNecessary() {
        int versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        SharedPreferences prefs = ...;
        if (prefs.getInt("lastUpdate", 0) != versionCode) {
            try {
                runUpdates();
    
                // Commiting in the preferences, that the update was successful.
                SharedPreferences.Editor editor = prefs.edit();
                editor.putInt("lastUpdate", versionCode);
                editor.commit();
            } catch(Throwable t) {
                // update failed, or cancelled
            }
        }
    }
    

提交回复
热议问题