初探SharedPreferences

android

android開發(fā)中,可能需要持久化少量的數(shù)據(jù),譬如說一些用戶設置的數(shù)據(jù),用數(shù)據(jù)庫就有點殺雞用牛刀了,這時候可以嘗試使用SharedPreferences。SharedPreferences是一種輕量級的存儲數(shù)據(jù)的方式,使用xml文件來進行鍵值對方式的存儲,而且使用起來非常輕量和快捷。

得到SharedPreferences:

SharedPreferences sharedPreferences =
getSharedPreferences("usable_sharedPreferences", Context.MODE_PRIVATE);

SharedPreferences使用一個內部類SharedPreferences.Editor來對數(shù)據(jù)進行編輯,得到edit:

SharedPreferences.Editor editor = sharedPreferences.edit();

提交數(shù)據(jù):

editor.putString("name", "簡書");
editor.putString("slogan", "交流故事,溝通想法");
editor.commit();

查詢數(shù)據(jù):

String value = sharedPreferences.getString(key,
"沒有找到鍵:" + key + " 對應的值,請檢查輸入的鍵!");

清空數(shù)據(jù):

editor.clear().commit();
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容