应用重新启动后,SharedPreferences不返回任何内容

时间:2019-06-12 05:46:11

标签: java android sharedpreferences

我使用此设置令牌方法将令牌保存在“共享首选项”中

"bootstrap": "4.3.1",
"jquery": "1.9.1 - 3",
"popper.js": "^1.14.7",
"node-sass": "4.7.2",

并在我所有的项目中使用此get Token方法获取令牌

public static void setToken(Context ctx, String token) {
        SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
        editor.putString(PREF_TOKEN, token);
        editor.apply();
    }

我的问题是应用重新启动时,获取令牌方法返回“ 456”

家庭活动令牌日志:

public static String getToken(Context ctx) {
            return getSharedPreferences(ctx).getString(PREF_TOKEN, "456");
        }

重启后:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjBkM2JlODBlMTg4Mzc4NTNjY2VjYjU2Nzg1NzAxYjNhM2NhZGJiOWFhYTZjYWIwNDQ3YjA4MzJmMzRkNmMxMzM5MzAyMWE2OWQ4NDk2ZTY1In0.eyJhdWQiOiIxIiwianRpIjoiMGQzYmU4MGUxODgzNzg1M2NjZWNiNTY3ODU3MDFiM2EzY2FkYmI5YWFhNmNhYjA0NDdiMDgzMmYzNGQ2YzEzMzkzMDIxYTY5ZDg0OTZlNjUiLCJpYXQiOjE1NjAzMTY5MTQsIm5iZiI6MTU2MDMxNjkxNCwiZXhwIjoxNTkxOTM5MzE0LCJzdWIiOiI1Iiwic2NvcGVzIjpbXX0.RovbkU1XXCuOcUvAzutW9Btm64BlYc8jAZTTeiPue43-YUMv2Ftr2m40I6yVH0JPdCGHwbtIruJRHeM8fx1ua4pryBQIxgdCvB-S5FiioOPR_zrG-II_pEquUQoz3wEpxmwG1KDmYOWfENA7El6v8e3mnyg54o9ikcYCFLgoV3V5kcdhX4RZRWeRE8ED76m1YhImjuIAkSV88tmtrzt1E7dWM_lfWDLGOsrPnOLFdzEGDozGHcMU6D5-qN9CroBGzrlLD4ngvk1yV1cypSLgsM9yuJ3b9MJJhcs5v_mrm5McT6aipcM6ghKdClGF7_SBAjREPJGxPD7-KY5sH4L9NkpsxH4SQL9fxKpE_Z2B_PCKVaCGtSBQ0E1dURFIkJfUWhFsRZea1DBXQkZTDcAnxj9WA2ZDqWe_Ve-fPDyhmnfObHfeJ0NRtm-Wgq6R-F5PwlF_SjxgrhXhKsAd4knvvkP-o06e_d3fb-8mUedmQQroI9VXci6kE5gJhqUWjX5OpCLWBCFY12Y5Vntg2R-G_sLPJXewkM7TcXlc381V212bJElFThgurWfm4zRfWA5L8VV8d_xms3f852rOg2z6xh0dNt5zeqp3b8IS68k1wTzBPGobJZSvr5ZDd_xZYpJREsDeLh8Osr7hP3V3zUWIMGdEyKUL3ITCL7FMAtj9VFA

2 个答案:

答案 0 :(得分:4)

简单的错误,您必须替换此行

SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();

到一个以下

SharedPreferences.Editor editor = getSharedPreferences(KEY_PREFS_NAME, context.MODE_PRIVATE).edit();

其中KEY_PREFS_NAME是您的偏好设置

答案 1 :(得分:0)

尝试保存该文件:

public void saveToken(String token){
    SharedPreferences sharedPreferences = getSharedPreferences(PREF_TOKEN, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(TOKEN, token).apply();
}

然后取回:

public String getToken(){
    SharedPreferences sharedPreferences = getSharedPreferences(PREF_TOKEN, Context.MODE_PRIVATE);
    return sharedPreferences.getString(TOKEN, "")
}

希望有帮助!