生活随笔
收集整理的這篇文章主要介紹了
SharedPreferences 使用方法详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
SharedPreferences是Android的一個接口類,是Android 數據存儲(保存內部)的一種方法。主要以.xml 的形式保存在Android /data/data/com.**包名/shared_prefs下,SharedPreferences類提供了一個通用框架,以便用戶能夠保存和檢索原始數據類型的鍵值對,原始數據類型如下:Boolean,Int,Float,Long,String。
歡迎關注微信公眾號:程序員Android
公眾號ID:ProgramAndroid
獲取更多信息
微信公眾號:ProgramAndroid
我們不是牛逼的程序員,我們只是程序開發中的墊腳石。
我們不發送紅包,我們只是紅包的搬運工。
通過本章學習你將掌握以下知識點
1. SharedPreferences的使用方法
2. SharedPreferences保存數據的方法
3. SharedPreferences讀取數據的方法
4. 總結SharedPreferencesUtils 封裝類使用方法
1. SharedPreferences的使用方法
SharedPreferences 使用方法如下
1. 創建保存數據的xml文件
2. 使用Editor 向xml文件中保存數據
3. commit() 保存數據
4. xml保存地方/data/data/com.***包名/shared_prefs
2. SharedPreferences 保存數據的方法
主要使用 putBoolean() 和 putString() 等方法添加值。
3. SharedPreferences讀取數據的方法
主要使用 getBoolean() 和 getString() 等 獲取保存的數據
4. 總結SharePerference Utils 封裝類使用方法
public class SharePerferenceUtils {private static SharedPreferences sp;// 1,存儲boolean變量方法public static void putBoolean(Context ctx, String key, boolean value) {// name存儲文件名稱if (sp == null) {sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);}sp.edit().putBoolean(key, value).commit();}// 2,讀取boolean變量方法public static boolean getBoolean(Context ctx, String key, boolean defValue) {// name存儲文件名稱if (sp == null) {sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);}return sp.getBoolean(key, defValue);}public static void putString(Context ctx, String key, String value) {// name存儲文件名稱if (sp == null) {sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);}sp.edit().putString(key, value).commit();}public static String getString(Context ctx, String key, String defValue) {// name存儲文件名稱if (sp == null) {sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);}return sp.getString(key, defValue);}/*** @param ctx* 上下文環境* @param key* 要從config.xml移除節點的name的名稱*/public static void removeKey(Context ctx, String key) {if (sp == null) {sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);}sp.edit().remove(key).commit();}// 反射(擴展)//public static void putInt(Context ctx, String key, int value) {// name存儲文件名稱if (sp == null) {sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);}sp.edit().putInt(key, value).commit();}public static int getInt(Context ctx, String key, int defValue) {// name存儲文件名稱if (sp == null) {sp = ctx.getSharedPreferences("config", Context.MODE_PRIVATE);}return sp.getInt(key, defValue);}}
保存數據
SharePerferenceUtils.putInt(getApplicationContext(), "int_key", 1);
獲取數據
SharePerferenceUtils.getString(getApplicationContext(), "string_key", "default_values");
至此 SharedPreferences的使用方法以基本完成。
注意:
SharedPreferences 保存在app內部,當手動清除APK 數據的時候,保存的數據會被清除掉
至此,本篇已結束,如有不對的地方,歡迎您的建議與指正。同時期待您的關注,感謝您的閱讀,謝謝!
如有侵權,請聯系小編,小編對此深感抱歉,屆時小編會刪除文章,立即停止侵權行為,請您多多包涵。
既然都看到這里,領兩個紅包在走吧!
以下兩個紅包每天都可以領取
1.支付寶搜索?522398497,或掃碼支付寶紅包海報。
支付寶掃一掃,每天領取大紅包
2.微信紅包,微信掃一掃即可領取紅包
?
微信掃一掃,每天領取微信紅包
小禮物走一走,來簡書關注我
總結
以上是生活随笔為你收集整理的SharedPreferences 使用方法详解的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。