How to clear old preferences when updating Android

2019-02-06 07:51发布

问题:

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 type was an Integer and in the most recent version it is now a String. I imagine this isn't good practice but unfortunately I had to do it.

My concern is that when someone updates to the new version their app will crash as the preference types have changed. For this reason I would like to clear the preferences whenever the app is updated (again I realise not ideal!)

Is this possible?

回答1:

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
        }
    }
}


回答2:

You can also append the version number while getting SharedPreferences like this

context.getSharedPreferences("MyKey" + app_version_no, Context.MODE_PRIVATE);

So if you update the app, the version number will change and you will have new set of preferences.



回答3:

Store version code in default SharedPreferences AND store your others preferences in version specified file , when the version change you can find your old version code and you can have your old preference file and update the new version by old data

int versionCode=0,oldVersion;
    try
    {
        versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
    }
    catch (PackageManager.NameNotFoundException e)
    {}
    SharedPreferences prefs =getSharedPreferences("MyPref" + versionCode, Context.MODE_PRIVATE);
    SharedPreferences prefsDefault = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);  


    oldVersion=prefsDefault.getInt("OldVersion",0);


    if (oldVersion!=versionCode)
    {
        if (oldVersion>0)
        {
            // ToDo Update Preferences
            String oldPrefsKey="MyPref" + oldVersion;
            SharedPreferences oldPrefs =context.getSharedPreferences(oldPrefsKey, Context.MODE_PRIVATE);
            SharedPreferences.Editor pEdit=prefs.edit();
            pEdit.putBoolean("clock24",oldPrefs.getBoolean("clock24",false));
            pEdit.putBoolean("show_clock",oldPrefs.getBoolean("show_clock",true));
            pEdit.commit();
            oldPrefs.edit().clear().commit();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                deleteSharedPreferences(oldPrefsKey);
            } else {
                try {
                    File oldFile=new File(getCacheDir().getParent() + "/shared_prefs/"+oldPrefsKey+".xml");
                    oldFile.delete();
                } catch (Exception e) {

                }
            }

        }
        prefsDefault.edit().putInt("OldVersion",versionCode).commit();




    }


回答4:

final String PREFERENCE_NAME = "my_preference";

final String APP_VERSION_CODE = 6; /*change this each time you want to clear
preference in updated app.*/

preferences = getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE);

if (preferences.getInt(PREFERENCE_VERSION, 0) != APP_VERSION_CODE) {
      preferences.edit().clear().apply();
      preferences.edit().putInt(PREFERENCE_VERSION, APP_VERSION_CODE).apply();
}