標籤:
在應用開發時,可能隨著需求或者其他因素,原設計的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) {// TODOversion = 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();
Android SharedPreferences 資料升級