SharedPreferences是Android平臺上一個輕量級的存儲輔助類,用來保存應用的一些常用配置,它提供了string,set,int,long,float,boolean六種數據類型。最終數據是以xml形式進行存儲。在應用中通常做一些簡單數據的持久化緩存。
SharedPreferences作爲一個輕量級存儲,所以就限制了它的使用場景,如果對它使用不當將會帶來嚴重的後果。我們大多時候都是用來存我們APP的sessionid這些比較簡單的數據,今天說一下SharedPreferences存取一個List,就直接貼出代碼了,裏面有註釋。
工具類
public class SpListUtil{
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
public SpListUtil(Context mContext, String preferenceName) {
preferences = mContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
editor = preferences.edit();
}
/**
* 保存List
* @param tag
* @param datalist
*/
public <T> void setDataList(String tag, List<DecBean> datalist) {
if (null == datalist || datalist.size() <= 0)
return;
Gson gson = new Gson();
//轉換成json數據,再保存
String strJson = gson.toJson(datalist);
editor.clear();
editor.putString(tag, strJson);
editor.commit();
}
/**
* 獲取List
* @param tag
* @return
*/
public List<DecBean> getDataList(String tag) {
List<DecBean> datalist=new ArrayList();
String strJson = preferences.getString(tag, null);
if (null == strJson) {
return datalist;
}
Gson gson = new Gson();
datalist = gson.fromJson(strJson, new TypeToken<List<DecBean>>() {
}.getType());
return datalist;
}
}
存數據
SpListUtil dataSave = new SpListUtil(this, "str");
dataSave.setDataList("strbean",list);
取數據
SpListUtil dataSave = new SpListUtil(this, "str");
List<DecBean> strbean = dataSave.getDataList("strbean");
到此就結束了,還是非常容易理解使用的。
會不定時更新安卓相關知識,喜歡的給點一下關注,感謝大家支持!!