android 将SharedPreferences做成简单工具
16lz
2022-01-11
这种处理主要是为了方便将项目的大多数数据存放在一个文件中/** * 向SharedPreferences中存储数据 * @param context * @param fileName * @param key * @param value */public static void setSharedPreferences(Context context, String fileName,String key, Object value) {if (context != null && fileName != null) {SharedPreferences sp = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);Editor editor = sp.edit();if (value instanceof Boolean) {editor.putBoolean(key, (Boolean) value);} else if (value instanceof Float) {editor.putFloat(key, (Float) value);} else if (value instanceof Integer) {editor.putInt(key, (Integer) value);} else if (value instanceof Long) {editor.putLong(key, (Long) value);} else if (value instanceof String) {editor.putString(key, (String) value);}editor.commit();}}/** * 获取SharedPreferences中存储的数据 * @param context * @param fileName * @param key * @param clazz * @return */public static Object getSharedPreferences(Context context, String fileName,String key, Class<?> clazz) {Object object = null;if (context != null && fileName != null && clazz != null) {SharedPreferences sp = context.getSharedPreferences(fileName,Context.MODE_PRIVATE);String name = clazz.getName().substring(10);if (name.equals("Boolean")) {object = sp.getBoolean(key, false);} else if (name.equals("Float")) {object = sp.getFloat(key, -1);} else if (name.equals("Integer")) {object = sp.getInt(key, -1);} else if (name.equals("Long")) {object = sp.getLong(key, -1);} else if (name.equals("String")) {object = sp.getString(key, null);}}return object;}
更多相关文章
- Android数据库操作的两种方式
- android之ListView和SimpleAdapter的组合使用
- 关于android 多媒体数据库
- Android(安卓)Bundle类
- Android(安卓)Linux Socket 数据传输错误
- 通过html页面打开Android本地的app
- android ContentProvider
- Android(安卓)Bundle类
- mybatisplus的坑 insert标签insert into select无参数问题的解决