天天看點

Android系列---SharedPreferences

Android系列—SharedPreferences

簡述:

Android持久化存儲的五種方式的一種,一般用來存儲應用簡單的配置資訊,可以儲存簡單的資料類型,也可以通過Base64編碼将二進制類型資料都以字元串的形式存儲其中,萬物皆二進制嘛
這種形式儲存的資料以* key-value *形式讀寫

(友善起見,以下簡稱SP)

使用方式:

1、擷取資料:
①、擷取SP對象

a、第一種:

該方式是通過Context來擷取,這種方式所生成的對象為整個應用共享該sp。

getSharedPreferences(String name, int mode);
  • 第一個參數(name):String類型,表示想要生成的檔案名,字尾為.xml;
  • 第二個參數(mode):int類型,表示存儲模式。

b、第二種:

這種是通過Activity來擷取,這種為目前Activity獨有的sp,是以它也不需要指定檔案名,隻要指定模式即可(mode)

②、調用getXxx()方法擷取相應的值
boolean b = sharedPreferences.getBoolean(key, false);
           

相應的方法有以下幾種:

getBoolean,getFloat,getInt,getString,getLong,getStringSet(String類型的Set集合),getAll(傳回的是個Map集合)

getXxx(String key,Xxx defValue)
  • 第一個參數(key):String類型的key,代表參數儲存時對應的參數名;
  • 第二個參數(defValue):與儲存的資料類型一緻,此處為boolean類型,代表當SP中沒有對應的值時,它作為預設值提供給應用。
二、儲存資料:
SharedPreferences sharedPreferences = context.getSharedPreferences(CONFIG, Context.MODE_PRIVATE);
//擷取SharedPreferences内部的Editor接口類型
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key,value);
editor.commit();
           

儲存資料得先擷取Editor的對象,由editor對象來進行儲存 ( putXxx ) 操作,最後類似資料庫,記得commit()即可。

保 存 數 據 的 putXxx 方 法 與 讀取數 據 的 getXxx 方 法 一 一 對 應,不過沒有putAll()方法。

注意commit()方法調用:

要麼像上面一樣分開寫,要麼用如下寫法:

不能這樣寫:

sharedPreferences.edit().putBoolean(key, value);
sharedPreferences.edit().commit();
           

原因:第二次調用edit()方法時傳回的是一個新的Editor對象,這就導緻第一個putXxx操作沒有commit()

————————華麗的分割線,後續遇到問題再更———————————-