Android 五種數(shù)據(jù)存儲的方式
- SharedPreferences:以Map形式存放簡單的配置參數(shù);
- ContentProvider:將應(yīng)用的私有數(shù)據(jù)提供給其他應(yīng)用使用秀仲;
- 文件存儲:以IO流形式存放默色,可分為手機(jī)內(nèi)部和手機(jī)外部(sd卡等)存儲球凰,可存放較大數(shù)據(jù);
- SQLite:輕量級、跨平臺數(shù)據(jù)庫呕诉,將所有數(shù)據(jù)都是存放在手機(jī)上的單一文件內(nèi)缘厢,占用內(nèi)存小甩挫;
- 網(wǎng)絡(luò)存儲 :數(shù)據(jù)存儲在服務(wù)器上贴硫,通過連接網(wǎng)絡(luò)獲取數(shù)據(jù);
Sharedpreferences是Android平臺上一個(gè)輕量級的存儲類伊者,用來保存應(yīng)用程序的各種配置信息英遭,其本質(zhì)是一個(gè)以“鍵-值”對的方式保存數(shù)據(jù)的xml文件,其文件保存在/data/data//shared_prefs目錄下删壮。
獲取SharedPreferences
要想使用 SharedPreferences 來存儲數(shù)據(jù)贪绘,首先需要獲取到 SharedPreferences 對象。Android中主要提供了三種方法用于得到 SharedPreferences 對象央碟。
Context類中的getSharedPreferences()方法:
此方法會接收兩個(gè)參數(shù):
- 第一個(gè)參數(shù):指定SharedPreferences文件的名稱税灌,如果指定的文件不存在則會創(chuàng)建一個(gè)
- 第二個(gè)參數(shù):指定操作模式
模式選擇:
- Context.MODE_PRIVATE:指定該SharedPreferences數(shù)據(jù)只能被本應(yīng)用程序讀、寫亿虽;(是默認(rèn)的操作模式和直接傳入0效果是相同)
- Context.MODE_WORLD_READABLE:指定該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序讀菱涤,但是不能寫;
- Context.MOED_WORLD_WRITEABLE:指定該該SharedPreferences數(shù)據(jù)能被其他應(yīng)用程序讀洛勉;(這兩種被棄用)
- Context.MODE_APPEND:該模式會檢查文件是否存在粘秆,存在就往文件追加內(nèi)容,否則就創(chuàng)建新文件收毫;
Activity類中的getPreferences()方法:
這個(gè)方法和 Context 中的 getSharedPreferences()方法很相似攻走,不過它只接收一個(gè)操作模式參數(shù),因?yàn)槭褂眠@個(gè)方法時(shí)會自動將當(dāng)前活動的類名作為 SharedPreferences 的文件名此再。
PreferenceManager類中的getDefaultSharedPreferences()方法:
這是一個(gè)靜態(tài)方法昔搂,它接收一個(gè) Context 參數(shù),并自動使用當(dāng)前應(yīng)用程序的包名作為前綴來命名 SharedPreferences 文件输拇。
SharedPreferences的使用
SharedPreferences對象本身只能獲取數(shù)據(jù)而不支持存儲和修改摘符,存儲修改是通過SharedPreferences.edit()獲取的內(nèi)部接口Editor對象的實(shí)現(xiàn)。使用Perferences來存儲數(shù)據(jù)策吠,用到了SharedPreferences接口和SharedPreferences的一個(gè)內(nèi)部接口SharedPreferences.Editor,這兩個(gè)接口在android.content包中:
1) 寫入數(shù)據(jù)
//步驟一:創(chuàng)建一個(gè)SharedPreferences對象
SharedPreferences sharedPreferences = getSharedPreferences("data",Context.MODE_PRIVATE);
//步驟二:實(shí)例化SharedPreferences.Editor對象
SharedPreferences.Editor editor = sharedPreferences.edit();
//步驟三:將獲取過來的值放入文件
editor逛裤。putString("name","Tom");
editor.putInt("age",28);
editor.putBoolean("marrid",false);
//步驟四:提交
editor.commmit();
2)讀取數(shù)據(jù):
SharedPreferences sharedPreferences = getSharedPreferences("data",Context.MODE_PRIVATE);
String userId = sharedPreferences.getString("name","");
3)刪除指定數(shù)據(jù)
editor.remove("name");
ediotor.commit();
4)清空數(shù)據(jù)
editor.clear();
editor.commit();
提交數(shù)據(jù)的時(shí)候用apply()會更好 commit()會立即將其數(shù)據(jù)寫入
注意:如果在 Fragment 中使用SharedPreferences 時(shí),需要放在onAttach(Activity activity)里面進(jìn)行SharedPreferences的初始化猴抹,否則會報(bào)空指針 即 getActivity()會可能返回null 带族!
工具類SharedPreferences
SharedPreferencesUtil](https://blog.csdn.net/a512337862/article/details/73633420)