Android SharedPreferences有时出现无法保存数据

qq_36050667 2017-09-03 09:58:57

这是工具类, 我需要根据用户的id去判断是不是需要重新登录, 第一次安装的时候, 登录进去,然后在后台杀死 , 然后下次打开是还是要重新登录, 通过log查看 sp中保存的值为空 , 但是第二次登录后之后就是好的, 求大神解答 到底是什么 ? 还有 SharedPreferences这个到底靠不靠谱 我第一次遇到这样的问题 很绝望








public class PreferenceUtils {
private static SharedPreferences preferences;
private static String NAME = "config";

private static SharedPreferences getPreferences(Context context) {
if (preferences == null) {
preferences = context.getSharedPreferences(NAME,
context.MODE_PRIVATE);
}
return preferences;
}

public static boolean getBoolean(Context context, String key) {
return getBoolean(context, key, false);

}

public static boolean getBoolean(Context context, String key,
boolean defValue) {
return getPreferences(context).getBoolean(key, defValue);

}

// 设置值,设置中心的值
public static void setBoolean(Context context, String key, boolean value) {
SharedPreferences preferences = getPreferences(context);
Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.apply();

}

public static String getString(Context context, String key) {
return getString(context, key, null);

}

public static String getString(Context context, String key, String defValue) {
return getPreferences(context).getString(key, defValue);

}

// 设置值,设置中心的值
public static void setString(Context context, String key, String value) {
SharedPreferences preferences = getPreferences(context);
Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();

}

// 设置值,设置中心的值
public static void setInt(Context context, String key, int value) {
SharedPreferences preferences = getPreferences(context);
Editor editor = preferences.edit();
editor.putInt(key, value);
editor.apply();

}

public static int getInt(Context context, String key, int defValue) {
return getPreferences(context).getInt(key, defValue);

}

public static int getInt(Context context, String key) {
return getInt(context, key, -1);

}

public static void clear(Context context) {
SharedPreferences preferences = getPreferences(context);
Editor editor = preferences.edit();
editor.clear();
editor.apply();
}
}

...全文
1015 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yixiu03 2018-12-09
  • 打赏
  • 举报
回复
作者可以把Context.PRIVATE改成这个这个模式Context.MODE_MULTI_PROCESS试试看
oXinShangRen 2017-09-05
  • 打赏
  • 举报
回复
这个和你SharedPreferences没有关系吧?SharedPreferences保存就是保存了删就是删了但都是你代码执行的不会自己无缘无故没有的,你还是检查你的代码吧。
qq_36050667 2017-09-04
  • 打赏
  • 举报
回复
这个我还是知道的呀, 就是 都试了 , 不行 ,所以才发帖问的 ,我以前就没有遇到过这个问题 最让人郁闷的是 为什么安装后第一次打开有值 然后后台杀死后 又没值 了 第二次之后 都是正常 不管怎么操作都有值
做人要简单 2017-09-04
  • 打赏
  • 举报
回复
apply() 是异步提交 如果有强烈的同步需求换成同步提交 commit试试

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧