android SharedPreferences使用

/**

? ? * 覆蓋式存儲(chǔ)

? ? *

? ? * @param mContext

? ? * @param key

? ? * @param content

? ? */

? ? public static void save(Context mContext, String key, String content) {

? ? ? ? SharedPreferences mSharedPreferences = mContext.getSharedPreferences("save", Context.MODE_PRIVATE);

? ? ? ? SharedPreferences.Editor editor = mSharedPreferences.edit();//SharedPreferences編輯的Editor對(duì)象

? ? ? ? editor.putString(key, content);

? ? ? ? editor.commit();//提交

? ? }

? ? /**

? ? * 取

? ? *

? ? * @param mContext

? ? * @param key

? ? * @return

? ? */

? ? public static String get(Context mContext, String key) {

? ? ? ? SharedPreferences mSharedPreferences = mContext.getSharedPreferences("save", Context.MODE_PRIVATE);

? ? ? ? String value = mSharedPreferences.getString(key, "");

? ? ? ? return value;

? ? }

? ? /***

? ? * 封裝通過(guò)sharedpreferences存值

? ? * @param context

? ? * @param key

? ? * @param object

? ? */

? ? public static void putInfo(Context context, String key, Object object) {

? ? ? ? SharedPreferences sp = context.getSharedPreferences("save", Context.MODE_PRIVATE);

? ? ? ? SharedPreferences.Editor editor = sp.edit();

? ? ? ? if (object instanceof String) {

? ? ? ? ? ? editor.putString(key, (String) object);

? ? ? ? } else if (object instanceof Integer) {

? ? ? ? ? ? editor.putInt(key, (Integer) object);

? ? ? ? } else if (object instanceof Boolean) {

? ? ? ? ? ? editor.putBoolean(key, (Boolean) object);

? ? ? ? } else if (object instanceof Long) {

? ? ? ? ? ? editor.putLong(key, (Long) object);

? ? ? ? } else {

? ? ? ? ? ? editor.putString(key, object.toString());

? ? ? ? }

? ? ? ? editor.commit();

? ? }

? ? /****

? ? *

? ? * 封裝通過(guò)sharedpreferences取值

? ? * @param context

? ? * @param key

? ? * @param defaultObject

? ? * @return

? ? */

? ? public static Object getInfo(Context context, String key, Object defaultObject) {

? ? ? ? SharedPreferences sp = context.getSharedPreferences("save", Context.MODE_PRIVATE);

? ? ? ? if (defaultObject instanceof String) {

? ? ? ? ? ? return sp.getString(key, (String) defaultObject);

? ? ? ? } else if (defaultObject instanceof Integer) {

? ? ? ? ? ? return sp.getInt(key, (Integer) defaultObject);

? ? ? ? } else if (defaultObject instanceof Boolean) {

? ? ? ? ? ? return sp.getBoolean(key, (Boolean) defaultObject);

? ? ? ? } else if (defaultObject instanceof Float) {

? ? ? ? ? ? return sp.getFloat(key, (Float) defaultObject);

? ? ? ? } else if (defaultObject instanceof Long) {

? ? ? ? ? ? return sp.getLong(key, (Long) defaultObject);

? ? ? ? }

? ? ? ? return null;

? ? }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容