里面的数据类型根据自己的类型所调整 public class UserInfoManager { private static UserInfoManager mInstance; private static final String USER_DATA = "user_data"; SharedPreferences sp; private UserInfoManager() { sp = MyApplition.context.getSharedPreferences("user_preferences", Context.MODE_PRIVATE); } public static UserInfoManager getInstance() { if (mInstance == null) { synchronized (UserInfoManager.class) { mInstance = new UserInfoManager(); } } return mInstance; } /** * 清空个人信息 */ public void clean() { sp.edit().clear(); } /** * 获取用户数据 * * @return */ public UserBean.RstBean getUserData() { String json = sp.getString(USER_DATA, null); if (TextUtils.isEmpty(json)) { return null; } Gson gson = new Gson(); Type type = new TypeToken<UserBean.RstBean>() { }.getType(); UserBean.RstBean user = null; try { user = gson.fromJson(json, type); } catch (Exception e) { } return user; } /** * 外部放入数据 * * @param userData */ public void setUserData(UserBean.RstBean userData) { if (userData != null) { Gson gson = new Gson(); setUserData(gson.toJson(userData)); } } /** * 放入用户数据 * * @param json */ private void setUserData(String json) { SharedPreferences.Editor editor = sp.edit(); editor.putString(USER_DATA, json); SharedPreferencesCompat.apply(editor); } /** * 优先使用SharedPreferences的apply方法,如果找不到则使用commit方法 */ private static class SharedPreferencesCompat { //查看SharedPreferences是否有apply方法 private static final Method sApplyMethod = findApply(); private static Method findApply() { try { Class cls = SharedPreferences.class; return cls.getMethod("apply"); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } /** * 如果找到则使用apply执行,否则使用commit */ public static void apply(SharedPreferences.Editor editor) { try { if (sApplyMethod != null) { sApplyMethod.invoke(editor); return; } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } editor.commit(); } } }
把多个页面要用的数据存放到本地
最新推荐文章于 2021-10-16 09:56:31 发布