在应用开发时,可能随着需求或者其他因素,原设计的SharedPreferences的值需要更改,这时我们该怎么做呢?
下面来看一个例子, 这是我们第一版开发的,
package com.laomou.demo;
import android.content.SharedPreferences;
public class PreferencesUpgrade {
public static final String KEY_LOCAL_VERSION = "pref_local_version_key";
public static final int CURRENT_LOCAL_VERSION = 0;
public static void upgradeLocalPreferences(SharedPreferences pref) {
int version;
try {
version = pref.getInt(KEY_LOCAL_VERSION, 0);
} catch (Exception ex) {
version = 0;
}
if (version == CURRENT_LOCAL_VERSION)
return;
SharedPreferences.Editor editor = pref.edit();
if (version == 0) {
// TODO
version = 1;
}
editor.putInt(KEY_LOCAL_VERSION, CURRENT_LOCAL_VERSION);
editor.apply();
}
}
随着需求或者其他因素,原设计的SharedPreferences的值需要更改,
比如KEY_PICTURE_SIZE 需要更改 为 1920x1152
这是我们的第二版代码
public class PreferencesUpgrade {
public static final String KEY_LOCAL_VERSION = "pref_local_version_key";
public static final int CURRENT_LOCAL_VERSION = 1;
public static void upgradeLocalPreferences(SharedPreferences pref) {
int version;
try {
version = pref.getInt(KEY_LOCAL_VERSION, 0);
} catch (Exception ex) {
version = 0;
}
if (version == CURRENT_LOCAL_VERSION)
return;
SharedPreferences.Editor editor = pref.edit();
if (version == 0) {
editor.putString(KEY_PICTURE_SIZE, "1920x1152");
editor.apply();
version = 1;
}
editor.putInt(KEY_LOCAL_VERSION, CURRENT_LOCAL_VERSION);
editor.apply();
}
}
再来看是如何做到更改SharedPreferences的值
更新版本号
public static final int CURRENT_LOCAL_VERSION = 1;
如果当前版本是0,那么则需要更新
if (version == 0) {
editor.putString(KEY_PICTURE_SIZE, "1920x1152");
editor.apply();
version = 1;
}
更新当前版本号
editor.putInt(KEY_LOCAL_VERSION, CURRENT_LOCAL_VERSION);
editor.apply();