Android SharedPreferences有时出现无法保存数据
这是工具类, 我需要根据用户的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();
}
}