前言
使用SharedPreferences 可以很方便的保存一些簡單的數據。可以保存的數據類型爲一些基本數據類型:String\ int\ long\ float\ boolean;集合類:Set,但是裏面只能存放String。可以將SharedPreferences 簡單的封裝成Helper類,以方便使用。
創建Helper類
- 創建類
PreferenceHelper
;寫上你的SharedPreferences 的標識;每個app可以有多個SharedPreferences
,使用標識來區分;
public class PreferenceHelper {
private static String IDENTIFY = "com.deeepthinking";
存儲String
- 需要傳入
key
和value
,每個key
對應一個value
;需要傳入系統的上下文環境Context
;保存的時候,需要使用SharedPreferences
的Editor
;保存完需要調用commit
完成保存;獲取數據需要key
獲取相應的value
;獲取的時候,可以指定默認值,當沒有值的時候,返回默認值;
public static void putString(String key, String value, Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IDENTIFY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(key, value);
editor.commit();
}
public static String getString(String key, Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IDENTIFY, Context.MODE_PRIVATE);
return sharedPref.getString(key, "");
}
存儲Set
public static void putSet(String key, Set<String> values, Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IDENTIFY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet(key, values);
editor.commit();
}
public static Set<String> getSet(String key, Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IDENTIFY, Context.MODE_PRIVATE);
return sharedPref.getStringSet(key, new HashSet<String>());
}
存儲int
public static void putInt(String key, int value, Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IDENTIFY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
public static int getInt(String key, Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IDENTIFY, Context.MODE_PRIVATE);
return sharedPref.getInt(key, 0);
}
刪除指定的數據
public static void removeData(String key, Context context) {
SharedPreferences sharedPref = context.getSharedPreferences(IDENTIFY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.remove(key);
editor.commit();
}
總結
- SharedPreferences只能存儲簡單的數據,不能存儲複雜的對象;
- 使用SharedPreferences可以方便存儲一些簡單的數據,比如設置,密碼等;
- 使用SharedPreferences保存需要用到Editor;
- 獲取數據的時候可以指定默認值;