How to clear old preferences when updating Android app?

后端 未结 4 1506
庸人自扰
庸人自扰 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:51

    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();
    
    
    
    
        }
    

提交回复
热议问题