android - 当应用程序被强制关闭或设备重新启动时,共享首选项会重置数据

标签 android sharedpreferences

我正在开发一个应用程序,我在其中将 usernamepassword 存储在 SharedPreferences 中。所有的事情对我来说都很好,存储和检索值。但我发现,当我重新启动设备或应用程序被强制关闭时,存储在 SharedPreferences 中的值被重置。当我再次启动我的应用程序时,我在 SharedPreferences 键中得到空值。这是我为存储值所做的工作:

SharedPreferences emailLoginSP;

emailLoginSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
emailLoginSP.edit().putString("prefEmailId", email_text).commit();
emailLoginSP.edit().putString("prefUserId", userIDToken).commit();
emailLoginSP.edit().putString("prefAccess_token", accessToken).commit();

Intent i = new Intent(LoginWithEmail.this,UserInfoActivity.class);
i.putExtra("acess_token", accessToken);
i.putExtra("user_id", userIDToken);
i.putExtra("emailID", email_text);
startActivity(i);

而且,这就是我检索它的方式:

SharedPreferences emailLoginSP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

loginEmail = emailLoginSP.getString("prefEmailId", null);
loginUserId = emailLoginSP.getString("prefUserId", null);
loginAccessToken = emailLoginSP.getString("prefAccess_token", null);

目前一切正常。 我再次说明我的问题,即当我强制关闭或重新启动我的设备时,我得到空值。我们可以将其永久存储在应用程序内存中吗?或者,我在这里做错了什么?

我们将不胜感激。

最佳答案

我有一个登录屏幕,并希望应用程序在关闭/销毁/电话调用/等后在内部屏幕上显示为好像它仍处于“登录”状态。

我有一个 Preferences 对象来保存 LoginRegister 之后的值。我在所有关键屏幕 onResume() 方法中读取偏好值。

登录后(举例):

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("sessionId", application.currentSessionId);
editor.putString("userId", application.currentUserId);
editor.putString("userEmail", application.currentUserEmail);
editor.putString("siteUserId", application.currentSiteUserId);
editor.commit();

在 Activity 的 onResume() 中: (即,在内部屏幕内)

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(activity);
application.currentSessionId = app_preferences.getString("sessionId", "");
application.currentUserId = app_preferences.getString("userId", "");
application.currentUserEmail = app_preferences.getString("userEmail", "");
application.currentSiteUserId = app_preferences.getString("siteUserId", "");

注意。我有应用程序“全局”变量,即 application.currentSessionId,您可以替换您的变量

尝试类似的方法,也许您没有正确保存或检索值,因为 SharePreferences 应该可以工作

关于android - 当应用程序被强制关闭或设备重新启动时,共享首选项会重置数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15353900/

相关文章:

android - SharedPreferences 的最佳实践

java - 从 sharedpreference 中删除所有数据

java - SharedPrefs 空指针 |这不是不可能吗?

android - AudioFlinger 无法创建记录轨道,状态 : -1 , 需要 ifx 帮助

android - 在哪里可以找到源代码链接

android - ubuntu 中的 adt 包不起作用

android - 如何以编程方式将 android 设备连接到 "WPA2 PSK"安全 wifi 热点网络?

java - 你如何阻止 Proguard 删除类型参数?

java - Roboguice 未注入(inject)对象并导致空指针异常

android - 微调器选择 - 保存到 SharedPreferences,然后检索