在應用開發時,可能隨着需求或者其餘因素,原設計的SharedPreferences的值須要更改,這時咱們該怎麼作呢?java
下面來看一個例子, 這是咱們初版開發的,android
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的值須要更改,app
好比KEY_PICTURE_SIZE 須要更改 爲 1920x1152spa
這是咱們的第二版代碼設計
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的值code
更新版本號orm
public static final int CURRENT_LOCAL_VERSION = 1;
若是當前版本是0,那麼則須要更新
ci
if (version == 0) { editor.putString(KEY_PICTURE_SIZE, "1920x1152"); editor.apply(); version = 1; }
更新當前版本號開發
editor.putInt(KEY_LOCAL_VERSION, CURRENT_LOCAL_VERSION); editor.apply();