我正在开发一个应用程序,我在其中将 username
和 password
存储在 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
对象来保存 Login
或 Register
之后的值。我在所有关键屏幕 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/