SharedPreferences介紹
SharedPreferences是android 的一種數(shù)據(jù)存儲(chǔ)方式 以key-value的鍵值對(duì)的方式 xml的格式存儲(chǔ)在內(nèi)存當(dāng)中 文件存放在/data/data//shared_prefs目錄下膜赃。SharedPreferences?
初始化
getSharedPreferences(name,mode)?
name 和 mode 連個(gè)參數(shù)分別代表 內(nèi)存空間命名 和 訪問權(quán)限模式?
name 內(nèi)存空間命名 也就是在內(nèi)存中開辟出屬于你app 的存儲(chǔ)空間?
mode 訪問權(quán)限?
MODE_APPEND: 追加方式存儲(chǔ)?
MODE_PRIVATE: 私有方式存儲(chǔ)?
MODE_WORLD_READABLE開放存儲(chǔ)方式 其他app可讀?
MODE_WORLD_WRITEABLE?開放存儲(chǔ)方式 其他app可寫獲得編輯對(duì)象
常用方法?
SharedPreferences.Editor edit = sp.edit();?
edit.clear();//清除數(shù)據(jù)?
edit.putString();//存入string?
edit.putInt(); //存入 int?
edit.putLong(); //存入 long?
edit.putBoolean(); // 存入boolean?
edit.putFloat(); //存入 float?
edit.putStringSet();// 存入集合?
sp.getString(); // 取string?
sp.getInt(); // 取int?
sp.getBoolean();//取boolean?
sp.getLong(); //取long?
sp.getAll(); // 取map
本人封裝的sp 管理工具
public classSPUtils{
?/** * sq 構(gòu)造 持有context 對(duì)象
?* @paramcontext
?*/?
?public static SharedPreferences sp;
? ? public static Context context;
? ? public? SPUtils(Context context) {
? ? ? ? this.context = context;
? ? ? ? if (sp==null){
? ? ? ? ? ? sp = context.getSharedPreferences(Constant.SPKEY, Context.MODE_PRIVATE);
? ? ? ? }
? ? }
? ? /**? ? * getString/char? ? ??
* @paramkey 字段名? ?
?* @returnvalue 返回值? ??
?*/? ?
?public static String getString(String key){
? ? ? ? String value = sp.getString(key, "");
? ? ? ? if (!TextUtils.isEmpty(value)){
? ? ? ? ? ? return value;
? ? ? ? }else {
? ? ? ? ? ? return Constant.BACKERROR+"";
? ? ? ? }
? ? }
? ? /**? ? *?
getInt方法? ??
?* @paramkey 字段名? ? *? ?
?* @returnvalue int返回值? ?
?*/??
? public static int getInt(String key){
? ? ? ? int value = sp.getInt(key, 0);
? ? ? ? if (value!=0){
? ? ? ? ? ? return value;
? ? ? ? }else {
? ? ? ? ? ? return Constant.BACKERROR;
? ? ? ? }
? ? }
? ? /**? ? * getLong 方法? ?
?*? ? * @paramkey 字段名? ??
?* @returnLong返回值? ?
?*/? ??
public static Long getLong(String key){
? ? ? ? Long value = sp.getLong(key, 0);
? ? ? ? if (value!=0){
? ? ? ? ? ? return value;
? ? ? ? }else {
? ? ? ? ? ? return Long.valueOf(Constant.BACKERROR);
? ? ? ? }
? ? }
? ? /**? ? *? putString 方法? ?
?*? ? * @paramkey 字段名? ?
?* @paramvalue 字段值? ?
?*/? ??
public static void putString(String key,String value){
? ? ? ? sp.edit().putString(key,value).commit();
? ? }
? ? /**? ? *? putInt 方法? ?
?*? ? * @paramkey 字段名? ?
?* @paramvalue 字段值? ?
?*/? ?
?public static void putInt(String key,int value){
? ? ? ? sp.edit().putInt(key,value).commit();
? ? }
? ? /**? ? *? putLong 方法? ??
?*? ? * @paramkey 字段名? ??
?* @paramvalue 字段值? ?
?*/??
? public static void putLong(String key,Long value){
? ? ? ? sp.edit().putLong(key,value).commit();
? ? }
? ? ? ? // 清除數(shù)據(jù)? ? public static void clearSpSpace(){
? ? ? ? sp.edit().clear().commit();
? ? }
}