import android.content.Context; import android.content.SharedPreferences; /** * Created by MnyZhao on 2017/11/15. * @author MnyZhao */ public class SpUtils { private static SharedPreferences preferences; public static void getPreference(Context context) { if (preferences == null) { preferences = context.getSharedPreferences("mysp", Context.MODE_PRIVATE); } } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param value 属性值 */ public static void putBoolean(Context context, String key, boolean value) { getPreference(context); preferences.edit().putBoolean(key, value).commit(); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param defaultValue 属性值 默认 */ public static boolean getBoolean(Context context, String key, boolean defaultValue) { getPreference(context); return preferences.getBoolean(key, defaultValue); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param value 属性值 */ public static void putFloat(Context context, String key, float value) { getPreference(context); preferences.edit().putFloat(key, value).commit(); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param defaultValue 属性值 默认 */ public static float getFloat(Context context, String key, float defaultValue) { getPreference(context); return preferences.getFloat(key, defaultValue); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param value 属性值 */ public static void putString(Context context, String key, String value) { getPreference(context); preferences.edit().putString(key, value).commit(); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param defaultValue 属性值 默认 */ public static String getString(Context context, String key, String defaultValue) { getPreference(context); return preferences.getString(key, defaultValue); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param value 属性值 */ public static void putLong(Context context, String key, long value) { getPreference(context); preferences.edit().putLong(key, value).commit(); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param defaultValue 属性值 默认 */ public static long getLong(Context context, String key, long defaultValue) { getPreference(context); return preferences.getLong(key, defaultValue); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param value 属性值 */ public static void putInt(Context context, String key, int value) { getPreference(context); preferences.edit().putInt(key, value).commit(); } /** * * @param context 上下文 最好用Application的context * @param key 属性名 * @param defaultValue 属性值 默认 */ public static int getInt(Context context, String key, int defaultValue) { getPreference(context); return preferences.getInt(key, defaultValue); } }
送你们一个SharedPreferences 的工具类
最新推荐文章于 2023-01-27 15:25:11 发布
本文介绍了一个针对Android中SharedPreferences的封装工具类SpUtils,该工具类简化了数据存储与读取的操作,支持多种数据类型如布尔值、浮点数、字符串等。
816

被折叠的 条评论
为什么被折叠?



