android - 如何使用新版本迁移 Android 首选项?

标签 android

我有一个应用程序,我在其中存储这样的用户首选项:

public static final String KEY_PREFS_LOGIN_INFO = "login_info";
public static final String KEY_PREFS_FILE_VERSIONs = "file_versions";
public static final String KEY_PREFS_LOGS = "logs";
public static final String KEY_PREFS_OTHERS = "others";

使用像这样的特定于 pref 的方法:

public static void setFileVersion(String key) {
    SharedPreferences settings = getAppContext().getSharedPreferences(KEY_PREFS_FILE_VERSIONS, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("current", key);
    editor.commit();
}

然后像这样检索值:

public static String filesVersion() {
    SharedPreferences settings = getAppContext().getSharedPreferences(KEY_PREFS_FILE_VERSIONS, 0);
    String current = settings.getString("current", "");
    return current;
}

我想要做的是将我所有的首选项存储在一个位置,这样我就可以使用一种通用方法来访问它们中的任何一个。我如何设置一种方法,以便在升级时将值从旧存储位置迁移到新存储位置?我正在寻找类似于 SQLiteOpenHelper 中的 onUpgrade() 方法的东西。

最佳答案

我会覆盖应用程序。然后在启动时检查您的共享首选项中存储的版本号,然后根据需要执行从任何旧 key 到新 key 的遍历。

public class MyApplication extends Application {
    private static final int CURRENT_PREFS_VERSION = 2;

    @Override
    public void onCreate() {
        super.onCreate();

        if(filesVersion() != CURRENT_PREFS_VERSION){
            migrate(filesVersion())
        }
    }

    private migrate(int oldVersion){

        switch(oldVersion){
            case 1:
                //get old preference, store new preference
                break;
        }

        setFileVersion(CURRENT_PREFS_VERSION)
    }

关于android - 如何使用新版本迁移 Android 首选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16397848/

相关文章:

java - Android - 旋转树

java - 无法将 Parcelable 放入 bundle 中

安卓 : Hide relativelayout when scroll down on listview

android - 监听更新并从服务器安装

Android Fabric - 以自定义间隔发送捕获的异常

android - 音频无法通过 HTTPS 在 chrome-android(LG G Pro 2 D838 上的 Kitkat 4.4.2)上播放

java - Appium:找不到可见的元素

android - 如何发送带有 Intent 的 zip 文件?安卓

android - 在 LinearLayout 中添加 View 时将方向更改为左侧

android - Android中如何定义滚动的ListView?