日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

android sharedpreferences工具类

發布時間:2024/4/15 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android sharedpreferences工具类 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

今天,簡單講講如何寫一個sharedpreferences的工具類。

?

很簡單,把一些重復的操作封裝在工具類里,其他地方調用就可以。在網上搜索了比較多的資料,找到一個比較好的工具類。

參考文章:https://blog.csdn.net/androidsj/article/details/79796194

import android.content.Context; import android.content.SharedPreferences;/*** 作者:Yzp on 2017-03-20 15:28* 郵箱:15111424807@163.com* QQ: 486492302* 用戶賬戶信息保存工具類*/ public class SharedPreferencesUtils {/*** 保存在手機里面的文件名*/private static final String FILE_NAME = "share_date";/*** 保存數據的方法,我們需要拿到保存數據的具體類型,然后根據類型調用不同的保存方法* @param context* @param key* @param object*/public static void setParam(Context context , String key, Object object){String type = object.getClass().getSimpleName();SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);SharedPreferences.Editor editor = sp.edit();if("String".equals(type)){editor.putString(key, (String)object);}else if("Integer".equals(type)){editor.putInt(key, (Integer)object);}else if("Boolean".equals(type)){editor.putBoolean(key, (Boolean)object);}else if("Float".equals(type)){editor.putFloat(key, (Float)object);}else if("Long".equals(type)){editor.putLong(key, (Long)object);}editor.commit();}/*** 得到保存數據的方法,我們根據默認值得到保存的數據的具體類型,然后調用相對于的方法獲取值* @param context* @param key* @param defaultObject* @return*/public static Object getParam(Context context , String key, Object defaultObject){String type = defaultObject.getClass().getSimpleName();SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);if("String".equals(type)){return sp.getString(key, (String)defaultObject);}else if("Integer".equals(type)){return sp.getInt(key, (Integer)defaultObject);}else if("Boolean".equals(type)){return sp.getBoolean(key, (Boolean)defaultObject);}else if("Float".equals(type)){return sp.getFloat(key, (Float)defaultObject);}else if("Long".equals(type)){return sp.getLong(key, (Long)defaultObject);}return null;}/*** 清除所有數據* @param context*/public static void clear(Context context) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);SharedPreferences.Editor editor = sp.edit();editor.clear().commit();}/*** 清除指定數據* @param context*/public static void clearAll(Context context) {SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);SharedPreferences.Editor editor = sp.edit();editor.remove("定義的鍵名");editor.commit();}}

?

android sharedpreferences工具類就講完了。

?

就這么簡單。

?

?

?

?

?

?

?

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的android sharedpreferences工具类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。